# Making Pong using Farseer Physics engine II

If you followed my last two posts (basics and part I), you will have a paddle and a ball setup in the game.

However, if you run the game, you’d observe the ball on collision with paddle; just blows it away. Instead, we’d want the ball to just bounce off.

There are two options:

• BodyType.Kinematic: We can make the paddle bodytype kinematic. This way, the ball would just bounce off the paddle. This however introduces another problem. Kinematic bodies don’t collide with other static/kinematic bodies. Thus, the paddle would not be restricted by the boundaries of the world box (unless, you manually cap it with hardcoded values).
• Fixed Prismatic Joint: There are good resources online to understand what this is. (Search for prismatic joint in box2d manual and here). It essentially restricts the body(s ) translation along one axis only. This fits the bill perfectly! (Remember bodies have to be dynamic type to be simulated for joint-physics).

Using Fixed prismatic joint we can restrict the paddle to move along only Y axis. Appetizer code follows:

`FixedPrismaticJoint fixedPrismJoint = new FixedPrismaticJoint(mBody, `
`mBody.Position, new Vector2(0, 1f));`

translates to: Create a joint for this body, at the given position, along the given axis (0, 1f). This way, the paddle is restricted to this axis, and moves only about the given position.

Setting limits to the movement of this joint:

```fixedPrismJoint.LowerLimit = -45f;
fixedPrismJoint.UpperLimit = 45f;
fixedPrismJoint.LimitEnabled = true;```

This would restrict (clamp) the body from moving beyond +/45 m along the given axis (0, 1f).

Automating movement using motors:

```fixedPrismJoint.MotorSpeed = 5.0f; // in meters / second

fixedPrismJoint.MaxMotorForce = 1000.0f; // maximum force in Newtons
fixedPrismJoint.MotorEnabled = true;
```
`This would put the motor into effect, which would the make body automatically oscillate between the bounds with MotorSpeed.`
`What good a joint is, if we don’t add it to the world:`
`Worldphy.AddJoint(fixedPrismJoint);`

That’s it! If you do this, you’ll have a paddle which only moves along Y axis, between those bounds and also simulates against the other elements in the world.

Divine Human Intervention:

```if (Input.IsNewKeyPress(Keys.W))
{
mBody.ApplyLinearImpulse(new Vector2(0f, 30.0f));
}
else if (Input.IsNewKeyPress(Keys.S))
{
mBody.ApplyLinearImpulse(new Vector2(0, -30.0f));
}```

This makes sure the paddle responds by trying to go up/down when you hit W/S.

This would let you make a complete pong game! But often in your game, you’d want to see debug information about the shapes. For the visual delight, there is a debug library that comes along with farseer. Its really easy to set it up and align your textures with the physics objects. More on that in the next tutorial!

# Making Pong using Farseer Physics engine

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:

`   1: mWorld = new World(Vector2.Zero);`

In CollisionManager.Update(gameTime); ticks the world:

`   1: mWorld.Step((float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.001f);`

By default, forces are automatically cleared in FPE, but in Box2D it is recommended to clear the forces.

`   1: mWorld.ClearForces();`

That is it! We’re done setting up the world.

Setting up the Ball:

GameOjbect just contains a reference to Body

`   1: public class Ball : GameObject`

Setting up the body:

`   1: mBody = BodyFactory.CreateBody(CollisionManager.Instance.Worldphy, new Vector2(10, 0));`

`   2:  `

`   3: mBody.CreateFixture(new CircleShape(1.0f, 0.5f ));`

`   4:  `

`   5: mBody.FixtureList[0].Restitution = 1f;`

`   6:  `

`   7: mBody.BodyType = FarseerPhysics.Dynamics.BodyType.Dynamic;`

`   8:  `

`   9: mBody.ApplyLinearImpulse(new Vector2(50, 0));`

1. Create a body in world at vector2(10, 0)
2. Creates a fixture out of a shape for mBody:
1. A circle shape with a radius of 1.0f is created
2. Density is 0.5f
3. 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.
1. 0 = fully absorb the collision : dont bounce at all : inelastic collision
2. 1 = perfect reflection : fully bounce back : elastic collision
4. Setting the bodyType to be Dynamic
5. Give the ball an initial ‘impulse’

`   1: public class Paddle : GameObject`

Setting up the body:

`   1: Fixture fix = FixtureFactory.CreateRectangle(CollisionManager.Instance.Worldphy, 1, 3, 0.5f, posn);`

`   2: fix.Restitution = 0f;`

`   3: fix.Friction = 0f;`

`   4:  `

`   5: mBody = fix.Body;`

`   6: mBody.BodyType = BodyType.Dynamic;`

This time we choose to create a body using fixtures.

1. 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)
2. We want the restitution to be 0 since we dont want the paddle to bounce off. See above for what restitution is!
3. Assign the body reference in fixture to body of parent GameObject
4. Make the BodyType to be dynamic

`   1: if (Input.IsNewKeyPress(Keys.W))`

`   2: {`

`   3:     mBody.ApplyForce(new Vector2(0f, 10.0f));`

`   4: }`

`   5: else if (Input.IsNewKeyPress(Keys.S))`

`   6: {`

`   7:     mBody.ApplyForce(new Vector2(0f, -10.0f));`

`   8: }`

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.

`   1: List<Vertices> borders = new List<Vertices>(4);`

`   2:  `

`   3: const float borderWidth = 0.2f;`

`   4: const float width = 40f;`

`   5: const float height = 25f;`

`   6:  `

`   7: //Bottom`

`   8: borders.Add(PolygonTools.CreateRectangle(width, borderWidth, new Vector2(0, height), 0));`

`   9:  `

`  10: //Left`

`  11: borders.Add(PolygonTools.CreateRectangle(borderWidth, height, new Vector2(-width, 0), 0));`

`  12:  `

`  13: //Top`

`  14: borders.Add(PolygonTools.CreateRectangle(width, borderWidth, new Vector2(0, -height), 0));`

`  15:  `

`  16: //Right`

`  17: borders.Add(PolygonTools.CreateRectangle(borderWidth, height, new Vector2(width, 0), 0));`

`  18:  `

`  19: List<Fixture> fixtures = FixtureFactory.CreateCompoundPolygon(mWorld, borders, 1, new Vector2(0, 0));`

`  20:  `

`  21: foreach (Fixture fixture in fixtures)`

`  22: {`

`  23:     fixture.Restitution = 1f;`

`  24:     fixture.Friction = 0;`

`  25: }`

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.

# Box2D / Farseer Physics Engine basics

I recently wanted to use a physics engine for the game, and I saw a lot of documentation scattered across manual and the code. This is my effort to document as much as I can and hopefully it helps someone who are about to get started!

I am using Farseer Physics Engine 3.2 which is a port of Box2D (along with some other extra tools). Let’s get started:

Common Objects in the physics system:

– World
– (Rigid)Body
– Shape
– Fixture

World: World is the heart of FPE. It makes the whole Physics world tick. There are multiple parameters that can be tweaked in this for efficiency, performance, accuracy etc.

Rigid Body: Hard chunk of matter that keeps a track of the position of the object

Shape: Object’s Geometrical shape like circle, rectangle, polygon etc

Fixture: Fixture binds a shape to a body and adds material properties to the object. (Material properties such as density(mass per volume), friction, and restitution)

PS: Memory management in Box2D recommends never to "new" / "malloc" Body, Joint and Fixtures, since it has its own memory management implemented(Small Object Allocators). This does not apply to FPE.

World:
– Create world:

`mWorld = new World(gravityVector); `

– Update World:

`mWorld.Step((float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.001f); -- ticks the world. `

Basics can be read at: Simulating the world; sec 2.4 at http://www.box2d.org/manual.html#_Toc258082968

# howto use Vertex Buffer objects(vbo) with opengl & Qt

This how-to concerns, including the functions needed for using Vertex Buffer Objects or VBOs; but in Qt framework. In short, this answers questions like:

How do I resolve this (when working in Qt)? “

This article at gamedev explains the process very well. The article is old, but I would recommend reading it since you then understand what the problem is and why is it giving you this error.

After you’re done reading that, you’d know that you are still using openGL v1.1 and need to access VBOs which is a feature of openGL v1.5. This is done by using v1.5 as extensions and interacting with the device drivers(assuming you have the latest drivers and they support v1.5), which is facilitated in code by specific function pointers.

By now, you’d know how to get this fixed if you were on a windows machine. But, I was using Qt and needed a way to get it to work with that. I came across these files:

glextensions.h and

glextensions.cpp

provided by Qt in one of there demos (boxes). These would resolve the functions you need for using VBOs. To get it to work, the code is not trivial.

After including the files in your header, one needs to “resolve()” the associated functions with a “context” (which is provided by the QGLWidget (or a class that you might have derived from it) ).

This is how I resolve them from within my class which derives from QGLWidget:

getGLExtensionFunctions().resolve(this->context() );

Functions like glGenBuffers, glBindBuffer, glBufferData etc are now ready to be used.

Also, I heard a lot of people using GLEW but I did not explore that route, so if you are stuck that might be something worthwile to checkout.

I hope it this article has saved you both, hours and tears. Let me know if you need any help.

(PS: When you call the resolve() function, the context should be available. I am still not 100% clear on how Qt manages the context for you, but I call it within InitializeGL(), since the context would be ready when the control reaches there. Also, take a look at the glextensions files to see they do pretty much the same thing as mentioned in the gamedev article )

# More screenshots : My Collada renderer now supports PolyList

Yayy! Let them screenshots do the talking 🙂 (Primitive: Polylist)

More stuff coming up!

# Screenie from my collada renderer / processor

While, I’ve not been posting for quite some time now, I got myself a prototype collada dae file reader and renderer working! It works for triangles primitives for now. Anyways, mumbo jumbo stuff is going to follow, but here is the screenshot of a “duck”.

 My output Original model images

I also have the normal, texture  and color information being processed and stored per vertex (just that I was too lazy to put in the code for rendering)

Yeeehaw !

# How to install CGAL (on Windows) and make it work with Visual Studio

• Run the executable and let it roll
• After the installer is done with its thing, fire up CMake-gui
• Use in-place compilation or otherwise (I prefer to make a “new folder” and make CMake output the solution files in that folder). I will assume that you do the same.
• PS: Choose Visual Studio 200X compiler depending on whichever compiler you use.
• Once CMake is done with generating VS .sln file, open it
• Do:
• Clean Solution
• Rebuild Solution
• Just two more things need to be done now..
• Include : Goto “new folder/include/CGAL” (in the new folder where cmake output its stuff): copy compiler_config.h to the “CGAL_DIR/include/CGAL”
• Lib :
• Make a new folder “lib” in CGAL_DIR/
• Copy “new folder/Debug/” (& release if you built it in release mode) to CGAL_DIR/lib (copy the *.lib and *.pdb)

Voila~ You’re done!