Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get angle from 2 positions

Tags:

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 = 246.500000, Object2Y = 441.500000 

I have tried the following and every variation under the sun:

double radians = ccpAngle(Object1,Object2); double degrees = ((radians * 180) / Pi);  

But I just get 2.949023 returned where I want something like 45 degrees etc.

like image 729
Jonathan Ogle-Barrington Avatar asked May 19 '11 20:05

Jonathan Ogle-Barrington


People also ask

How do you find the angle of rotation with two points?

The angle of rotation between the two points or vertices is the number of central angles times the measure of a single central angle: angle of rotation =m×α = m × α .


2 Answers

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.

like image 60
Tomas McGuinness Avatar answered Sep 21 '22 18:09

Tomas McGuinness


Here's how I'm doing it in Swift for those interested, it's based on @bshirley's answer above w/ a few modifications to help match to the calayer rotation system:

extension CGFloat {     var degrees: CGFloat {         return self * CGFloat(180) / .pi     } }  extension CGPoint {     func angle(to comparisonPoint: CGPoint) -> CGFloat {         let originX = comparisonPoint.x - x         let originY = comparisonPoint.y - y         let bearingRadians = atan2f(Float(originY), Float(originX))         var bearingDegrees = CGFloat(bearingRadians).degrees          while bearingDegrees < 0 {             bearingDegrees += 360         }          return bearingDegrees     } } 

This provides a coordinate system like this:

        90 180              0         270 

Usage:

point.angle(to: point2) CGPoint.zero.angle(to: CGPoint(x: 0, y: 1)) // 90 
like image 44
Logan Avatar answered Sep 21 '22 18:09

Logan