我正在使用CoreMotion收集加速度计数据来改变精灵的位置。为此,您需要使用块并更新到队列。但是,这样做与cocos2d scheduleUpdate冲突。这是Core 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。我该如何解决这个问题?
非常感谢你的帮助。
P.S。这是我的错误
*** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason:
'CCScheduler: You can't re-schedule an 'update' selector'.
Unschedule it first'
答案 0 :(得分:0)
问题是每帧都会调用加速度计块,因此您无法在那里安排更新。
只需在init中安排一次更新。然后使用BOOl iVar /属性来跟踪您的更新方法是否应该处理它正在做什么。
或者移动块内的所有更新代码。毕竟,加速计值会更新每一帧,因此您实际上不会错过“更新”。