如何根据加速度计的x坐标旋转精灵?

时间:2015-12-16 13:13:45

标签: ios objective-c sprite-kit cmmotionmanager

我的角色需要左右移动和旋转。移动工作都很好,但我不满意旋转。我希望角色在向左或向右移动时才会旋转。当角色不移动时,旋转需要停止。模仿光滑的滚动。

我尝试旋转SKAction,见下文:

if(_shouldMoveToRight) {
    SKAction *moveAction = [SKAction moveTo:CGPointMake(_destX, _destY) duration:1];
    [_character runAction:moveAction];

    SKAction *rotateAction = [SKAction rotateByAngle:0.2 duration:1];
    [_character runAction:rotateAction];
}
if (_shouldMoveToLeft) {
    SKAction *moveAction = [SKAction moveTo:CGPointMake(_destX, _destY) duration:1];
    [_character runAction:moveAction];

    SKAction *rotateAction = [SKAction rotateByAngle:0.2 duration:1];
    [_character runAction:rotateAction];

这使角色一直移动。任何帮助表示赞赏!

移动代码:

self.manager = [[CMMotionManager alloc] init];
if ([self.manager isAccelerometerAvailable] == YES) {
    [self.manager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
                                        withHandler:^(CMAccelerometerData *data, NSError *error)
     {
         _destX = 0.0, _destY = 0.0;
         _currentX = _character.position.x;
         _currentY = _character.position.y;

         _shouldMoveToRight = NO;
         _shouldMoveToLeft = NO;

         if(data.acceleration.y < -0.25) { // tilting the device to the right
             _destX = _currentX + (data.acceleration.x * kPlayerSpeed);
             _destY = _currentY;
             _shouldMoveToRight = YES;
             _shouldMoveToLeft = NO;
         } else if (data.acceleration.y > 0.25) { // tilting the device to the left
             _destX = _currentX + (data.acceleration.x * kPlayerSpeed);
             _destY = _currentY;
             _shouldMoveToRight = NO;
             _shouldMoveToLeft = YES;
         }
     }];
}

0 个答案:

没有答案