2

Is there an easy way to do this.

I have a CGPoint pointA (10, 10) and another CGPoint pointB (15, 8). I need to get a CGPoint which is on the same line as the one connecting A and B and at a certain distance (say 2) before point A.

I tried looking around for any vector based struct. There is something called CGVector but that seems to be pretty useless here.

OutOnAWeekend
  • 1,383
  • 1
  • 18
  • 36
  • 1
    This question I think is simliar to this: http://stackoverflow.com/questions/2969181/moving-cgpoint-a-certain-distance-along-a-certain-heading-iphone and should help you solve your issue. –  Feb 16 '17 at 13:38
  • 2
    @Sneak, I am sure this is similar to this and the question you posted http://math.stackexchange.com/questions/175896/finding-a-point-along-a-line-a-certain-distance-away-from-another-point – KrishnaCA Feb 16 '17 at 13:42
  • @KrishnaCA Yeah I saw that too, good to link it too gj. –  Feb 16 '17 at 13:44

1 Answers1

1

It can be done like this:

Assumption: The direction of line is from head:(point2) tail:(point1)

- (CGPoint)getPointFromLineConnecting:(CGPoint)point1 andPoint2:(CGPoint)point2 withDistanceFromPoint1:(CGFloat)dist {

    // distance between connecting points
    CGFloat distance = sqrtf(powf(point1.x-point2.x, 2) + powf(point1.y-point2.y, 2)); 

    // unit vector point: v = (x1-x0)i/distance + (y1-y0)j/distance
    CGPoint unitVectorPoint = CGPointMake((point2.x - point1.x)/distance, (point2.y - point1.y)/distance); 

    // resultant point at a distance d from p1 
    CGPoint resultPoint = CGPointMake((point1.x+dist*unitVectorPoint.x), (point1.y+dist*unitVectorPoint.y));

    return resultPoint;
}
KrishnaCA
  • 5,615
  • 1
  • 21
  • 31
  • 1
    @Sneak, I rechecked it and resolved an issue. I believe it should work fine now – KrishnaCA Feb 16 '17 at 14:09
  • Pretty close. The only assumption in the above code snippet is that its an ascending line. But I can figure that part out. Will come back and mark this as an answer, unless something even better is suggested. – OutOnAWeekend Feb 16 '17 at 14:41
  • @AnandKumar, I believe that the edited answer satisfies all the conditions – KrishnaCA Feb 17 '17 at 06:06