物体在加速度计中移动

时间:2012-06-05 10:55:38

标签: cocos2d-iphone accelerometer ccsprite acceleration

我想在cocos2d中创建一个游戏,其中一个对象正在运行。

我想在设备加速度计的基础上左右移动此对象。 我得到加速度计的值并更新对象的位置。即使我可以在LOG中看到新的位置。但是对象并没有从它的角度出发。这里是我在应用程序中编写的代码。

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration1 {

acceleration = acceleration1;
CGPoint position = mainPlayer.position;

if(acceleration.y < -0.25) {  // tilting the device to the right
    position.y -= 0.25;
} else if (acceleration.y > 0.25) {  // tilting the device to the left
    position.y += 0.25;
} else {

} //    newPosition = position;

CCAction *action = [CCMoveTo actionWithDuration:0.01 position:position];
[mainPlayer runAction:action]; 
//    mainPlayer.position = ccp(position.x, position.y);
}

我通过直接设置位置和使用操作来尝试两种方式。

任何人都知道为什么会出现这个问题或任何需要加速度计工作的设置。

请提供此类举例的任何链接。

2 个答案:

答案 0 :(得分:0)

尝试使用MoveBy而不是MoveTo:

 - (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration1 {

    acceleration = acceleration1;
    CGPoint position = ccp(0,0);

    if(acceleration.y < -0.25) {  // tilting the device to the right
        position.y = 0.25;
    } else if (acceleration.y > 0.25) {  // tilting the device to the left
        position.y = 0.25;
    }

    CCAction *action = [CCMoveBy actionWithDuration:0.01 position:position];
    [mainPlayer runAction:action]; 
 }

答案 1 :(得分:0)

我建议不要从加速度计运行动作,因为这种方法被称为10秒一次(我不记得cocos2d如何初始化加速度计),这会导致runAction方法被调用10次一秒钟,可能会停止前一个动作,这就是为什么你没有看到它移动。

显示有关如何创建主播放器以及如何将其添加到场景/图层的更多代码

相关问题