Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting radian angle to CGVector

Using Sprite Kit I am trying to set an SKPhysicsBody moving according to a given angle, so for example if you wanted the sprite to travel to the right you would specify 1.571 radians. To turn the specified angle into a velocity I am using the method below to convert radians to a CGVector. The ORIGINAL version that I implemented from memory has the strange effect of offsetting all the angles by 90degrees. (i.e. if 0 degrees is used the sprite moves right (just like it would if you specified 90degrees)

Question:

I have fixed this in the NEW version by swapping the dx and dy assignments. My question is why does this happen, do I have it wrong in the original (there do seem to be others doing it that way on the web) or is there some reason based on the particular coordinate system being used.

// ORIGINAL
- (CGVector)convertAngleToVector:(CGFloat)radians {
    CGVector vector;
    vector.dx = cos(radians) * 10;
    vector.dy = sin(radians) * 10;
    NSLog(@"DX: %0.2f DY: %0.2f", vector.dx, vector.dy);
    return vector;
}


// NEW, SWAPPED DX & DY
- (CGVector)convertAngleToVector:(CGFloat)radians {
    CGVector vector;
    vector.dy = cos(radians) * 10;
    vector.dx = sin(radians) * 10;
    NSLog(@"DX: %0.2f DY: %0.2f", vector.dx, vector.dy);
    return vector;
}

NOTE: also in Sprite Kit clockwise rotations are negative, so far convertAngleToVector is doing positive clockwise rotations (i.e. 1.571 radians is right, where it should be left) I could just do cos(radians*-1) and sin(radians*-1) but there might be some underlying reason for this based on me swapping dx and dy.

Sprite Kit (SKView Coordinates):

enter image description here

like image 645
fuzzygoat Avatar asked Oct 08 '13 16:10

fuzzygoat


1 Answers

Yeah, SpriteKit defaults to the right. The Physics Collision sample project solves this by implementing this method:

- (CGFloat)shipOrientation
{
    // The ship art is oriented so that it faces the top of the scene, but Sprite Kit's rotation default is to the right.
    // This method calculates the ship orientation for use in other calculations.
    return self.zRotation + M_PI_2;
}

You can then just get the existing orientation by calling something like:

CGFloat shipDirection = [self shipOrientation];

And then adjust the zRotation property from there.

like image 197
macshome Avatar answered Oct 01 '22 00:10

macshome