Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPoint offset by pixels toward angle?

Let me just start with the code.

- (NSPoint*) pointFromPoint:(NSPoint*)point withDistance:(float)distance towardAngle:(float)angle; {
    float newX = distance * cos(angle);
    float newY = distance * sin(angle);

    NSPoint * anNSPoint;
    anNSPoint.x = newX;
    anNSPoint.y = newY;

    return thePoint;
}

This should, based on my knowledge, be perfect. It should return and x value of 0 and a y value of 2 if I call this code.

somePoint = [NSPoint pointFromPoint:somePoint withDistance:2 towardAngle:90];

Instead, I get and x value of 1.05 and a y of 1.70. How can I find the x and y coordinates based on an angle and a distance?

Additional note: I have looked on math.stackexchange.com, but the formulas there led me to this. I need the code, not the normal math because I know I will probably screw this up.

like image 470
Justin Avatar asked Apr 11 '26 03:04

Justin


1 Answers

A working version of your function, which accepts values in degrees instead of radians, would look like this:

- (NSPoint)pointFromPoint:(NSPoint)origin withDistance:(float)distance towardAngle:(float)angle
{
    double radAngle = angle * M_PI / 180.0;
    return NSMakePoint(origin.x + distance * cos(radAngle), point.y + distance * sin(radAngle));
}
like image 126
Noah Witherspoon Avatar answered Apr 12 '26 17:04

Noah Witherspoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!