Get angle from 2 positions

后端 未结 6 1242
失恋的感觉
失恋的感觉 2020-12-08 15:18

I have 2 objects and when I move one, I want to get the angle from the other.

For example:

Object1X = 211.000000, Object1Y = 429.000000
Object2X = 24         


        
6条回答
  •  一整个雨季
    2020-12-08 16:04

    Does this other answer help?

    How to map atan2() to degrees 0-360

    I've written it like this:

    - (CGFloat) pointPairToBearingDegrees:(CGPoint)startingPoint secondPoint:(CGPoint) endingPoint
    {
        CGPoint originPoint = CGPointMake(endingPoint.x - startingPoint.x, endingPoint.y - startingPoint.y); // get origin point to origin by subtracting end from start
        float bearingRadians = atan2f(originPoint.y, originPoint.x); // get bearing in radians
        float bearingDegrees = bearingRadians * (180.0 / M_PI); // convert to degrees
        bearingDegrees = (bearingDegrees > 0.0 ? bearingDegrees : (360.0 + bearingDegrees)); // correct discontinuity
        return bearingDegrees;
    }
    

    Running the code:

    CGPoint p1 = CGPointMake(10, 10);
    CGPoint p2 = CGPointMake(20,20);
    
    CGFloat f = [self pointPairToBearingDegrees:p1 secondPoint:p2];
    

    And this returns 45.

    Hope this helps.

提交回复
热议问题