Game Development Reference
In-Depth Information
pos.x + = playerVelocity.x;
// The Player should also be stopped from 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 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;
}
A boundary check prevents the player sprite from leaving the screen. Once again, you
have to take the player texture's contentSize into account, because the player posi-
tion is at the center of the sprite image, but you don't want either side of the image to
be off the screen. For this, you calculate imageWidthHalved and then use it to
check whether the newly updated player position is within the left and right border lim-
its. The code may be a bit verbose at this point, but that makes it easier to understand.
Build and run the project now to see how controlling the player feels like.
Tip You'll notice that this straightforward implementation of accelerometer
control doesn't give you the same dynamic feeling that you may be used to
from games like Tilt to Live. The reason is that smooth, dynamic accelerometer
controls require accelerometer filtering. The KKInput class in Kobold2D al-
Search Nedrilad ::




Custom Search