Published by
Mar 13, 2011 (last update: Mar 13, 2011)

Moving along lines

Score: 3.4/5 (33 votes)
*****
Many people know what a line is, and many more can draw them using slope. But I've noticed that when trying to draw a line using only the origin and end points, people stumble and fall.

The question is quite simple: How can I draw something without a concrete x and y coordinate?

The answer is also simple: You find them.

Let us imagine you wish to move an object from the origin point (0,0) to a certain end point (8,20). Well, a human would simply realize that (8, 20) translates into a slope of 2/5 (2 up, 5 right) and draw the line accordingly. Unfortunatly, a computer doesn't possess a ruler with which to draw the line. So the person is forced to tell the computer every single point the line goes through. This is done quite easily. In this example, we are moving up and over. So, we already have the Y coordinates. They are points 1 through 20.

But how to get X? It's easy, X is a function of Y. Like so: X=(X1/Y1)*Y

To get a better idea:

X= X1 * Y
__Y1

In this equation, X1 is 8 (the target point's X coordinate) and Y1 is 20 (the target point's Y coordinate). As for Y, simply substitute 1 through 20 to get the X coordinates for it.

The program sample would look like this:

1
2
3
4
5
6
7
8
9
10
11
float X1=8, Y1=20;
     float x[20], y[20];
     for (int i=1; i<21; i++)
     {
         y<i>=i;
         x<i>=(X1/Y1)*y<i>;
     }
     for (int i=1; i<21; i++)
     {
         cout<<"y["<<i<<"]="<<y<i><<" x["<<i<<"]="<<x<i><<endl;
     }


Which creates the following output:

y[1]=1 x[1]=0.4
y[2]=2 x[2]=0.8
y[3]=3 x[3]=1.2
y[4]=4 x[4]=1.6
y[5]=5 x[5]=2
y[6]=6 x[6]=2.4
y[7]=7 x[7]=2.8
y[8]=8 x[8]=3.2
y[9]=9 x[9]=3.6
y[10]=10 x[10]=4
y[11]=11 x[11]=4.4
y[12]=12 x[12]=4.8
y[13]=13 x[13]=5.2
y[14]=14 x[14]=5.6
y[15]=15 x[15]=6
y[16]=16 x[16]=6.4
y[17]=17 x[17]=6.8
y[18]=18 x[18]=7.2
y[19]=19 x[19]=7.6
y[20]=20 x[20]=8