Converting radian angle to CGVector

2020-06-04 04:08发布

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

2条回答
SAY GOODBYE
2楼-- · 2020-06-04 04:27

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.

查看更多
做个烂人
3楼-- · 2020-06-04 04:41

From the Sprite Kit Programming Guide (emphasis added):

Sprite Kit also has a standard rotation convention. Figure 4-2 shows the polar coordinate convention. An angle of 0 radians specifies the positive x axis. A positive angle is in the counterclockwise direction.

In this coordinate system, an angle of zero radians pointing to the right is correct. If you want to use a system in which a zero angle is straight up (along positive y axis) and increase clockwise, you'll want to transform your angles before converting them to vectors.

查看更多
登录 后发表回答