Game Development Reference
In-Depth Information
Note In this example, the CCPhysicsNode (the player's parent node) has a
default gravity force set in its properties. Default gravity will continue to accel-
erate the player downward, unless you combat the effect by applying an
upward-oriented impulse.
Imposing a Speed Limit on the Player
The last block of code checks whether the physicsBody.velocity has exceeded a
safe value, and if it has, changes the velocity to the maximum speed while preserving the
direction:
if (ccpLength(physicsBody.velocity) > _playerMaxVelocity)
{
CGPoint direction = ccpNormalize(physicsBody.velocity);
physicsBody.velocity = ccpMult(direction,
_playerMaxVelocity);
}
Normalizing the velocity turns it into a unit vector; a vector whose length is 1 but keeps
pointing in the same direction as the original. Multiplying this vector by _player-
MaxVelocity makes velocity's length equal to _playerMaxVelocity while still
pointing in the same direction. This effectively prevents the speed from exceeding
_playerMaxVelocity . Without this code fragment, the user could keep a finger on
the screen to make the player accelerate indefinitely.
Tip The ccpLength , ccpNormalize and ccpMult C functions are all
declared in the CGPointExtension.h file, alongside other 2D vector func-
tions. To quickly access their declaration, right-click anywhere on a keyword in
the Xcode editor and select “Jump to Definition” from the context menu. Try it
now with whatever keywords, variables, properties, etc. you're interested in.
You'll notice it doesn't just reveal the origins but also brings you to related code
fragments and documentation comments. This is a great way to learn more
about the code you're using.
By now, you may be wondering what unit velocity is. It's measured in points per second
(pt/s). If you wanted to move a body from the left to the right side of a landscape iPad
Search WWH ::




Custom Search