Search code examples
objective-cxcodephysicsvector-graphicschipmunk

Random movement using physics, CGPoint, vectors, a little confused on the physics/math side of things


I've managed to get Chipmunk physics and some other stuff to lay down a ball on my screen, and I can affect the gravity with some buttons / accelerometer. Yay me!

Next up, I'd like to turn off the gravity, and simulate a top-down view, where that ball moves around the screen of its own volition. I can apply forces to the ball using body -> f = cpv(dx, dy), but I'm not quite up on my physics and mathematics, so I'm trying to understand how the two values I feed it cause the movement.

I understand that positive values will move it right or down, and negative values will move it left or up, but that's about all I'm understanding at this point.

If I wanted to, say, pick a random compass bearing (0 - 359 degrees) and move it on that bearing, how would such a value translate into a vector?

I've created this method, but it's not working as expected and I'm unsure what I'm doing wrong:

- (CGPoint) getVectorFromAngle: (float) angle AndMagnitude: (float) magnitude
{
    float x = magnitude * cos(angle);
    float y = magnitude * sin(angle);
    CGPoint point = CGPointMake(x, y);
    NSLog(@"Made a CGPoint of X: %f and Y: %f.", point.x, point.y);
    return point;
}

If I feed it an angle of 45 and a magnitude of 10, it creates X as 5.253220 and 8.509035. However, the calculator found here shows that it should create X and Y as 7.0711.

What do I have wrong here?


Solution

  • sin and cos take angles in radians, multiply your angles by π/180.