Game Development Reference
In-Depth Information
// controls how quickly velocity decelerates (lower = quicker to change direction)
float deceleration = 0.4f;
// determines how sensitive the accelerometer reacts (higher = more sensitive)
float sensitivity = 6.0f;
// how fast the velocity can be at most
float maxVelocity = 100;
// adjust velocity based on current accelerometer acceleration
playerVelocity.x = playerVelocity.x * deceleration + acceleration.x * sensitivity;
// we must limit the maximum velocity of the player sprite, in both directions
if (playerVelocity.x > maxVelocity)
playerVelocity.x = maxVelocity;
else if (playerVelocity.x <- maxVelocity)
playerVelocity.x = - maxVelocity;
Now playerVelocity will be changed, but how do you add the velocity to the
player's position? By scheduling the update method in the GameLayer init meth-
od, adding this line:
// schedules the -(void) update:(ccTime)delta method to be called every frame
[self scheduleUpdate];
You also need to add the -(void) update:(ccTime)delta method as shown
in Listing 4-7 . The scheduled update method is called every frame, and that's where
you add the velocity to the player position. This way, you get a smooth constant move-
ment in either direction regardless of the frequency of accelerometer input.
Listing 4-7 . Updating the Player's Position with the Current Velocity
-(void) update:(ccTime)delta
// Keep adding up the playerVelocity to the player's position
CGPoint pos = player.position;
Search Nedrilad ::

Custom Search