我想在 cocos2d 中创建一个正在运行一个对象的游戏。
我想根据设备加速度计从左右移动此对象。我正在获取加速度计的值并更新对象的位置。甚至我可以在日志中看到新位置。但是物体并没有从它的财产中移动。这是我在应用程序中编写的代码。
- (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); }
我已经通过直接设置位置和使用动作来尝试这两种方式。
任何人都知道为什么会出现此问题或任何需要加速度计工作的设置。
请为此类示例提供任何链接。
尝试使用 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];
}
我建议不要从加速度计运行操作,因为此方法在一秒钟内被调用了 10 次(我不记得 cocos2d 是如何初始化加速度计的),这将导致 runAction
方法每秒调用 10 次,并可能停止上一个动作,这就是为什么你看不到它移动的原因。
显示有关如何创建主播放器以及如何将其添加到场景/图层的更多代码