Reputation: 63
Suppose I have 2 points (x1,y1)o----------------o(x2,y2)
.
What I'm trying to do is to get the new coordinate as I move along the line by distance d from (x1,y1). However I realized that the further I move away from (x1,y1) the new coordinate starts to become more and more inaccurate (i.e. it strays away from the original line). My solution is based on the last answer provided in https://math.stackexchange.com/questions/25286/2d-coordinates-of-a-point-along-a-line-based-on-d-and-m-where-am-i-messing. Is there something wrong I'm doing here? Or is there a class in objective-c that can do the same thing?
Thanks!
float signu, signv;
float x, y;
float x1 = cp1.x;
float y1 = cp1.y;
float x2 = cp2.x;
float y2 = cp2.y;
float d = noOfSteps*pixelsPerStep;
float m = (y2-y1)/(x2-x1);
float u = d/ABS(sqrt(m*m+1));
float v = m*u;
if(x1-x1<=0)
signu = -1;
if(y2-y1<=0)
signv = -1;
x = x1 + signu*u;
y = y1 + signv*v;
Upvotes: 1
Views: 98
Reputation: 80287
Try standard method of vector algebra:
Norm = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
Assert Norm != 0
//components of direction vector
Dir_X = (x2 - x1) / Norm
Dir_Y = (y2 - y1) / Norm
x = x1 + d * Dir_X
y = y1 + d * Dir_Y
Upvotes: 1