基于加速度计的运动

时间:2012-08-01 17:15:46

标签: iphone cocos2d-iphone

现在开始使用加速度计来左右移动玩家精灵。 我使用了本教程:COCOS2D_ACCELEROMETER_MOVEMENT 这只能在某个时候工作......有些时候不动......我怎么解决这个问题? 以下是我的示例:See this Sample 感谢您阅读此内容...我的代码出了什么问题?还有其他办法吗?

这是我的代码:

#define kHeroMovementAction 1
#define kPlayerSpeed 500
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    // use the running scene to grab the appropriate game layer by it's tag

    // grab the player sprite from that layer using it's tag
    CCSprite *playerSprite = mPlayer;
    float destX, destY;
    BOOL shouldMove = NO;

    float currentX = playerSprite.position.x;
    float currentY = playerSprite.position.y;

    if(acceleration.x > 0.25) {  // tilting the device upwards
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else if (acceleration.x < -0.25) {  // tilting the device downwards
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else 

        if(acceleration.y < -0.25) {  // tilting the device to the right
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else if (acceleration.y > 0.25) {  // tilting the device to the left
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else {
        destX = currentX;
        destY = currentY;
    }

    if(shouldMove) 
    {
        CGSize wins = [[CCDirector sharedDirector] winSize];
        // ensure we aren't moving out of bounds     
        if(destX < 30 || destX > wins.width - 30 || destY < 30 || destY > wins.height - 100) {
            // do nothing
        } else {
            CCAction *action = [CCMoveTo actionWithDuration:0.5f position: CGPointMake(destX, playerSprite.position.y)];
            [playerSprite stopActionByTag:kHeroMovementAction];
            [action setTag:kHeroMovementAction];
            [playerSprite runAction:action];
        }
    } else {
        // should stop
        [playerSprite stopActionByTag:kHeroMovementAction];
    }

}

更新:此处为best way to do this.

1 个答案:

答案 0 :(得分:1)

你应该看看Ray Wenderlich的滚动教程here

他的加速计部分靠近页面底部。