objective-ccocos2d-iphonecgpointbox2d-iphoneios-4.2

Finding CGPoint by adding into distance of two CGPoints


I have two CGPoints A and B. Distance between A and B can be found with ccpDistance(A,B).

With this information, I need to find programmatically CGPoint(x,y) of X by adding small distance into distance of A-B. A-B may can make a connecting line in horizontal, vertical, diagonal or any orientation. Purpose is to extend the imaginary line and find a point at the end of it.

Is it possible in Box2D for iOS? If Yes, then how?

          X            Y   X
         /               .  \ 
        /                  . \
       B                     .B
      /                        \
     /                          \
    /                            \
   /                              \
  A                                A

Solution

  • Use the following function (put it in one of your .h files):

    static inline CGPoint
    ccpLineExtend(const CGPoint v1, const CGPoint v2, const CGFloat extension)
    {
        double angle = atan2(v2.y - v1.y, v2.x - v1.x);
        return ccp(v2.x + extension * cos(angle), v2.y + extension * sin(angle));
    }