2012-12-11 27 views
0

我正在使用CoreMotion收集加速计数据以更改精灵的位置。为了做到这一点,你需要使用一个块并更新到一个队列。但是,这样做与cocos2d scheduleUpdate冲突。这里是核心self.motionManager代码=Updatoqueue和Cocos2d scheduleUpdate冲突

[[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

问题是加速度计块被调用每一帧,所以你不能在那里安排更新。

只需在init中调度一次即可。然后使用BOOl iVar /属性来跟踪您的更新方法是否应该处理它正在执行的任何操作。

或者移动块内的所有更新代码。毕竟,加速计值更新每一帧,所以你不会错过“更新”。

+0

谢谢,这总是显而易见的,我想念。顺便说一下,感谢您编写您的书籍Learn Cocos2D,对于我通过对Cocoa环境和编程的全新掌握而感到欣喜。 – AlexHeuman