Question

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
Was it helpful?

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));
}

OTHER TIPS

I suggest the following method which doesn't make use of any triangular function. I suppose it's faster than Lukman's suggestion but I didn't measure times.

static inline CGPoint ccpLineExtend(const CGPoint from, const CGPoint to, const CGFloat factor)
{
    return CGPointMake(from.x + factor * (to.x - from.x), from.y + factor * (to.y - from.y));
}

factor = 1.0 means that the resulting point is equal to point to. factor = 2.0 means that the resulting point is as twice as far from from as to is.

@Lars's answer was best and simplest for me. Here is the Swift 4 version:

let newPoint = CGPoint(x: origin.x + factor * (end.x - origin.x), y: origin.y + factor * (end.y - origin.y))

If you have the current distance, you can add and subtract from it or change it altogether by calculating:

let factor = newDistance/currentDistance

In my case, I had a distance calculator from CGPoint to CGPoint using an extension:

extension CGPoint {
    func distance(to point: CGPoint) -> CGFloat {
        let x = self.x - point.x
        let y = self.y - point.y
        return sqrt(pow(x, 2) + pow(y, 2))
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top