Game Development Reference
good job of simulating a pinball game, would still require a lot of tweaking and
fine-tuning of the ball's behavior and collision responses for everything to feel
just right and to be a fair and fun pinball table. PhysicsEditor can help you with
the tweaking of values by providing you a single, convenient interface for edit-
ing any shape's physics parameters.
The setBallStartPosition method repositions the ball somewhere in the area
where you'll later add the plunger. By slightly randomizing the ball's position, the
plunger will later shoot the ball into play more realistically, meaning unpredictably to
some extent. Whenever the ball falls into the drain, the setBallStartPosition
method is called again to place the ball back to its start position.
// set the ball's position
float randomOffset = CCRANDOM_0_1() * 10.0f - 5.0f;
CGPoint startPos = CGPointMake(305 + randomOffset, 80);
physicsBody- > SetTransform([Helper toMeters:startPos], 0.0f);
physicsBody- > SetLinearVelocity(b2Vec2_zero);
physicsBody- > SetAngularVelocity(0.0f);
The physicsBody- > SetTransform method positions the ball's body, and as
with all bodies in this example game, the PhysicsSprite class takes care of syn-
chronizing the body's sprite with the body's position. The position in pixels must of
course be converted to Box2D's meter units, which is done by using the Helper
class's toMeters method. The second parameter of the SetTransform method is
the rotation of the body .
Just changing the body's position isn't enough. The body would still keep its current
velocity (angular and linear) and would simply keep on moving. The last two lines of
the setBallStartPosition method thus reset the linear and angular velocity of
the body to 0. Linear velocity determines a body's speed and direction, whereas angu-
lar velocity determines how fast and in which direction the body rotates.