2012-08-01 100 views
0

現在開始使用加速度計向左和向右移動玩家精靈的遊戲。 我使用了本教程:COCOS2D_ACCELEROMETER_MOVEMENT 這隻適用於某些時候......有些時候不能移動......我該如何解決這個問題? 這裏是我的示例:See this Sample 感謝您閱讀此...我的代碼有什麼問題?有沒有其他方法?基於加速度計的移動

這裏是我的代碼:

#define kHeroMovementAction 1 
#define kPlayerSpeed 500 
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { 

    // use the running scene to grab the appropriate game layer by it's tag 

    // grab the player sprite from that layer using it's tag 
    CCSprite *playerSprite = mPlayer; 
    float destX, destY; 
    BOOL shouldMove = NO; 

    float currentX = playerSprite.position.x; 
    float currentY = playerSprite.position.y; 

    if(acceleration.x > 0.25) { // tilting the device upwards 
     destX = currentX - (acceleration.y * kPlayerSpeed); 
     destY = currentY + (acceleration.x * kPlayerSpeed); 
     shouldMove = YES; 
    } else if (acceleration.x < -0.25) { // tilting the device downwards 
     destX = currentX - (acceleration.y * kPlayerSpeed); 
     destY = currentY + (acceleration.x * kPlayerSpeed); 
     shouldMove = YES; 
    } else 

     if(acceleration.y < -0.25) { // tilting the device to the right 
     destX = currentX - (acceleration.y * kPlayerSpeed); 
     destY = currentY + (acceleration.x * kPlayerSpeed); 
     shouldMove = YES; 
    } else if (acceleration.y > 0.25) { // tilting the device to the left 
     destX = currentX - (acceleration.y * kPlayerSpeed); 
     destY = currentY + (acceleration.x * kPlayerSpeed); 
     shouldMove = YES; 
    } else { 
     destX = currentX; 
     destY = currentY; 
    } 

    if(shouldMove) 
    { 
     CGSize wins = [[CCDirector sharedDirector] winSize]; 
     // ensure we aren't moving out of bounds  
     if(destX < 30 || destX > wins.width - 30 || destY < 30 || destY > wins.height - 100) { 
      // do nothing 
     } else { 
      CCAction *action = [CCMoveTo actionWithDuration:0.5f position: CGPointMake(destX, playerSprite.position.y)]; 
      [playerSprite stopActionByTag:kHeroMovementAction]; 
      [action setTag:kHeroMovementAction]; 
      [playerSprite runAction:action]; 
     } 
    } else { 
     // should stop 
     [playerSprite stopActionByTag:kHeroMovementAction]; 
    } 

} 

更新:這裏是best way to do this.

+0

我在這裏得到了正確的解決方案:http://gamedev.stackexchange.com/questions/33412/accelerometer-to-move-player-left-and-right/33427#33427 – Guru 2012-08-02 04:16:03

+1

好的。快樂的編碼! – Jeeter 2012-08-02 19:10:19

回答

1

你應該看看雷Wenderlich的滾動教程here

他的加速度計的部分是靠近頁面底部。

+0

感謝您提供的信息,Ray Wenderlich的教程中的「Tanks」示例在我的設備中也無法一直運行..oh:iPod Touch 4G,iOS5 ....在該運動中是隨機方向。但我需要用於只是左側和右側的設備傾斜。 – Guru 2012-08-02 02:30:54

+0

你需要做什麼然後只是實現Y方向加速 – Jeeter 2012-08-02 19:09:06

+0

我試過也......但它停了一段時間...無論如何,我遵循這種替代方式:http://gamedev.stackexchange.com/questions/33412 /加速計對移動玩家 - 左 - 右/ 33427#33427 – Guru 2012-08-03 12:33:55