1
votes

I have the last two CGPoints from a Array which contains points of line drawn by the user . i need to extend the line upto a fixed distance at the same angle. so i first calculate the angle between the last two points with the help of following code

-(CGFloat)angleBetweenFirstPoint:(CGPoint)firstPoint ToSecondPoint:(CGPoint)secondPoint
{

CGPoint diff = ccpSub(secondPoint, firstPoint);

NSLog(@"difference point %f , %f",diff.x,diff.y);

CGFloat res = atan2(diff.y, diff.x);

/*if ( res < 0 ) 
{
    res = (0.5 * M_PI) + res;
}

if ( dx<0  && dy>0 ) {      // 2nd quadrant
    res += 0.5 * M_PI;
} else if ( dx<0 && dy<0 ) {        // 3rd quadrant
    res += M_PI;
} else if ( dx>0 && dy<0 ) {        // 4th quadrant
    res += M_PI + (0.5 * M_PI);
}*/

//res=res*180/M_PI;

res = CC_RADIANS_TO_DEGREES(res);

return res;
}

After calculating the angle i find the extend point with the help of following maths

-(void)extendLine
{
lineAngle = [self angleBetweenFirstPoint:pointD ToSecondPoint:endPt];

extendEndPt.x = endPt.x - cos(lineAngle) * 200;
        extendEndPt.y = endPt.y - sin(lineAngle) * 200;

// draw line unto extended point
}

But the point i am getting is not right to draw the extended line at the same angle as the original line. I think it is because i am not getting the right angle between those last points.. what am i possibly doing wrong?? Do i need to consider the whole quadrant system while considering the angle and how? and m working in landscape mode. does that make any difference??

1

1 Answers

8
votes

Ye gods, you are doing this in a way that is WILDLY INCREDIBLY over-complicated.

Skip all of the crapola with angles. You don't need it. Period. Do it all with vectors, and very simple ones. First of all, I'll assume that you are given two points, P1 and P2. You wish to find a new point P3, that is a known distance (d) from P2, along the line that connects the two points.

All you need do is first, compute a vector that points along the line in question.

V = P2 - P1;

I've written it as if I am writing in MATLAB, but all this means is to subtract the x and y coordinates of the two points.

Next, scale the vector V to have unit length.

V = V/sqrt(V(1)^2 + V(2)^2);

Dividing the components of the vector V by the length (or 2-norm if you prefer) of that vector creates a vector with unit norm. That norm is just the square root of the sum of squares of the elements of V, so it is clearly the length of the vector.

Now it is simple to compute P3.

P3 = P2 + d*V;

P3 will lie at a distance of d units from P2, in the direction of the line away from point P1. Nothing sophisticated required. No angles computed. No worry about quadrants.

Learn to use vectors. They are your friends, or at the least, they can be if you let them.