Using Accelerometer for Sprite Movement
via: http://www.cocos2d-iphone.org/wiki/doku.php/tips:using_accelerometer_for_sprite_movement
init{
}
init{
self.isAccelerometerEnabled = YES;
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1/60];
}
#define kHeroMovementAction 1 #define kPlayerSpeed 100 - (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { // use the running scene to grab the appropriate game layer by it's tag GameLayer *layer = (GameLayer *)[[[CCDirector sharedDirector] runningScene] getChildByTag:kTagGameLayer]; // grab the player sprite from that layer using it's tag CCSprite *playerSprite = (CCSprite *)[layer getChildByTag:kTagSpritePlayer]; 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:1 position: CGPointMake(destX, destY)]; [action setTag:kHeroMovementAction]; [playerSprite runAction:action]; } } else { // should stop [playerSprite stopActionByTag:kHeroMovementAction]; } }
Comments
Post a Comment