-2

I have a 2D Coordinate system where The Origin Starts at the top Left (Y Is higher as I move downward) I am Given Two Points in Space, Lets Say Point A, and Point B. How can I determine that next Point on the line From Point A to Point B? For example, I have Point A(10, 10) and Point B (1,1) I know the point I'm looking for is (9,9). But how do I do this mathematically? For say a more complicated Set of points A(731, 911) and B(200, 1298)

I'm trying to move my mouse, one pixel at a time from its current location to a new one.

This doesn't work, but honestly I'm stumped where to begin.

int rise = x2 - 460; //(460 is Point A x)
int run = y2 - 360;//(360 is Point A Y)
float slope = rise / run;
int newx = x1 + ((slope / slope) * 1); //x1 Is my current mouse POS x
int newy = y1 + (slope * -1);//y1 is my current mouse Pos y

It almost works but seems inverted, and wrong.

2 Answers2

2

You already have the slope, so to get the next point on the line (there are infinitely many), you have to choose a step value or just arbitrarily pick one of the points.

Given A(y1, x1), your goal in finding a new point, B(y2, x2) is that it must satisfy the equation: (y2 - y1) / (x2 - x1) = slope.

To simplify, (x2 - x1) * slope = y2 - y1

You already have x1, slope, y1, and you can choose any arbitrary x2, so when you plug all those into the equation, you can simplify it further to:

y2 = (x2 - x1) * slope + y1


To illustrate this with your other points (A(731, 911) and C(200, 1298)) and say you want to find a new point B, we can proceed as follows:

Find the slope first:

float slope = (1298 - 911) / (200 - 731); // -0.728813559322

Choose x and solve for y:

x1 = 731, slope = -0.728813559322, y1 = 911 Choose x2 = 500 and solving for y2, we get:

float y2 = (500 - 731) * -0.728813559322 + 911; // 1079.355932203382

So your new point is:

B(500, 1079.355932203382)

You can verify this new point still has the same slope to point C

smac89
  • 39,374
  • 15
  • 132
  • 179
0

With A = (x1,y1) and B = (x2,y2) the line is (expressed in two same equations):

(1)   y = (x-x1)*(y2-y1)/(x2-x1) + y1
(2)   x = (y-y1)*(x2-x1)/(y2-y1) + x1

To find next point, put x1+1 (or x1-1 you know) in equation (1) and find y and also put y1+1 or y1-1 in equation (2) and find x.

You can decide which one is better choice. Take care of vertical or horizontal lines, where one of the equations won't work.

NOTE: do not cast floating point result to int. Do round instead.

Ali Tavakol
  • 405
  • 3
  • 11