I'm using CoreMotion to gather accelerometer data to change the position of a sprite. In order to do this you need to use a block and update to a queue. However, doing this conflics with the cocos2d scheduleUpdate. Here is the code for 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];
}];
}
and this is the code for my schedule update:
/*************************************************************************/
//////////////////////////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;
}
I know that I can bypass using scheduleUpdate and put the update code inside of the first block, but I still want to be able to use scheduleUpdates. How do I get around this?
Thank you very much for your help.
P.S. This is my error
*** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason:
'CCScheduler: You can't re-schedule an 'update' selector'.
Unschedule it first'