我正在使用 CoreMotion 收集加速度计数据以更改精灵的位置。为此,您需要使用块并更新到队列。但是,这样做会与 cocos2d scheduleUpdate 发生冲突。这是核心 self.motionManager = 的代码
[[CMMotionManager alloc] init];
if (motionManager.isAccelerometerAvailable) {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[self.motionManager
startAccelerometerUpdatesToQueue:queue
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
// Deceleration
float deceleration = 0.4f; // Controls how fast velocity deceerates/low = quck to change dir
// sensitivity
float sensitivity=0.6f;
//how fast the velocity can be at most
float maxVelocity=100;
// adjust the velocity basedo n current accelerometer acceleration
playerVelocity.x = playerVelocity.x*deceleration+accelerometerData.acceleration.x*sensitivity;
// we must limit the maximum velocity of the players sprite, in both directions
if (playerVelocity.x>maxVelocity) {
playerVelocity.x=maxVelocity;
}else if (playerVelocity.x < -maxVelocity) {
playerVelocity.x = -maxVelocity;
}
// schedule the -(void)update:(ccTime)delta method to be called every frame
[self scheduleUpdateWithPriority:0];
}];
}
这是我的日程更新的代码:
/*************************************************************************/
//////////////////////////Listen for Accelerometer/////////////////////////
/*************************************************************************/
-(void) update:(ccTime)delta
{
// Keep adding up the playerVelocity to the player's position
CGPoint pos = player.position;
pos.x += playerVelocity.x;
// The player should also be stopped form going outside the screen
CGSize screenSize = [CCDirector sharedDirector].winSize;
float imageWidthHalved = player.texture.contentSize.width * 0.5f;
float leftBorderLimit = imageWidthHalved;
float rightBorderLimit = screenSize.width - imageWidthHalved;
// preventing the player sprite from moving outside of the screen
if (pos.x < leftBorderLimit) {
pos.x=leftBorderLimit;
playerVelocity=CGPointZero;
} else if (pos.x>rightBorderLimit)
{
pos.x=rightBorderLimit;
playerVelocity = CGPointZero;
}
// assigning the modified position back
player.position = pos;
}
我知道我可以绕过 scheduleUpdate 并将更新代码放在第一个块中,但我仍然希望能够使用 scheduleUpdates。我该如何解决这个问题?
非常感谢您的帮助。
PS这是我的错误
*** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason:
'CCScheduler: You can't re-schedule an 'update' selector'.
Unschedule it first'