如何以直角旋转CGVector?

时间:2014-05-27 15:55:07

标签: ios objective-c sprite-kit

我想将精灵的方向存储为CGVector

我只有4个可能的载体:

CGVector up     = CGVectorMake(0,    100);
CGVector down   = CGVectorMake(0,   -100);
CGVector left   = CGVectorMake(-100,    0);
CGVector right  = CGVectorMake(100,   0);

我有2个事件:

-(void) turnLeft;
-(void) turnRight;

如果现在(my_sprite.direction == CGVector(0,100))和事件turnRight发生了怎样才能得到CGVector(100, 0) ???

P.S。我不想要很多if或switch语句,因为将来应该有更多的向量。

2 个答案:

答案 0 :(得分:2)

让我们按照这个顺序重新排列你的向量:

CGVector up     = CGVectorMake(   0,    100);
CGVector right  = CGVectorMake( 100,      0);
CGVector down   = CGVectorMake(   0,   -100);
CGVector left   = CGVectorMake(-100,      0);

现在我们可以看到顺时针旋转90度的矢量与交换坐标然后否定Y坐标相同:

CGVector vectorByRotatingVectorClockwise(CGVector in) {
    CGVector out;
    out.dx = in.dy;
    out.dy = -in.dx;
    return out;
}

答案 1 :(得分:2)

由于您希望将来能够使用更多方向,因此最好只存储角度和速度。

- (void)applyDirectionChange{
    CGFloat x = sinf(self.angle)*self.speed;
    CGFloat y = cosf(self.angle)*self.speed;
    self.direction = CGVectorMake(x,y);
}  

- (void)turnRight{
    self.angle += 90*M_PI/180;
    [self applyDirectionChange];
}

- (void)turnLeft{
    self.angle -= 90*M_PI/180;
    [self applyDirectionChange];
}

如果您仍想保留常量向量,请按正确顺序将它们放入数组中,并使当前方向索引指向右向量:

//declarations
NSUInteger currentDirectionIndex;
NSUInteger numDirections;
CGVector[4] directions;

//initialize them somewhere
currentDirectionIndex = 0;
numDirections = 4; 
directions[0] = up;
directions[1] = right;
directions[2] = down;
directions[3] = left;

//in your methods
- (void)turnRight{
    currentDirectionIndex++;
    if(currentDirectionIndex>=numDirections)
        currentDirectionIndex = 0;

    self.direction = directions[currentDirectionIndex];
}

- (void)turnLeft{
    currentDirectionIndex--;
    if(currentDirectionIndex<0)
        currentDirectionIndex = numDirections-1;

    self.direction = directions[currentDirectionIndex];
}