Making Pong using Farseer Physics enginePosted: January 28, 2011
In my attempt to learn farseer physics engine(3.2), I decided to make a pong game, using the engine and XNA 4.0. Physics engine is an overkill for pong, but it sure helps to learn some of the basic concepts in a simple environment.
Please see my last post about some of the basic knowledge you need to get started.
This post is not about software design, and this is just my way of doing things.
Setting up the world:
I made a CollisionManager which contains the World from FPE, and exposes it as a property which others can use.
Creates a world with no gravity:
In CollisionManager.Update(gameTime); ticks the world:
By default, forces are automatically cleared in FPE, but in Box2D it is recommended to clear the forces.
That is it! We’re done setting up the world.
Setting up the Ball:
GameOjbect just contains a reference to Body
Setting up the body:
- Create a body in world at vector2(10, 0)
- Creates a fixture out of a shape for mBody:
- A circle shape with a radius of 1.0f is created
- Density is 0.5f
- For the fixture attached to body, we want to set the restitution. Restitution is a measure of bounciness of a collision (elasticity of collision). Value should be between 0 and 1.
- 0 = fully absorb the collision : dont bounce at all : inelastic collision
- 1 = perfect reflection : fully bounce back : elastic collision
- Setting the bodyType to be Dynamic
- Give the ball an initial ‘impulse’
Setting up a Paddle:
Paddle also inherits from GameObject:
Setting up the body:
This time we choose to create a body using fixtures.
- Create a fixture in world, with a body at position: ‘posn’ and rectangle shape of width 1 unit and height 3 units (units are in the MKS system) (I pass the posn as a vector2 in the constructor of Paddle)
- We want the restitution to be 0 since we dont want the paddle to bounce off. See above for what restitution is!
- Assign the body reference in fixture to body of parent GameObject
- Make the BodyType to be dynamic
Moving the paddle:
When W is pressed, we want the paddle to move up (we apply a force in up direction with magnitude of 10f). When S is pressed, we want the paddle to move down (we apply a force in down direction with magnitude of -10f).
That’s it. Instantiate a paddle and a Ball and you’ll see a ball moving towards right and if you press W/S the paddle would move either up/down.
You’ll also notice the ball to fly off the screen because there is nothing to bound it. I used this code from one of the testSamples for farseer to generate a big box, which would prevent the ball or paddle to fly away.
By default, the bodyType is static, which is what we’d want the outer box to be.
The code is very intuitive if you followed the above post and read the basics in my last post.