Making Pong using Farseer Physics engine II
Posted: February 1, 2011 Filed under: Game Development | Tags: box2d, Farseer Leave a comment »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:
In Paddle::Update():
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
Posted: January 28, 2011 Filed under: Game Development | Tags: box2d, Farseer 3 Comments »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));
- 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:
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.
- 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:
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
Posted: January 28, 2011 Filed under: Game Development | Tags: box2d, Farseer 1 Comment »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
Posted: October 31, 2009 Filed under: Game Development | Tags: howto, openGL, qt, vbo 1 Comment »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:
“ glGenbuffers : identifier not found error
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
Posted: October 13, 2009 Filed under: Announcements, Game Development | Tags: collada 2 Comments »Yayy! Let them screenshots do the talking
(Primitive: Polylist)
More stuff coming up!
Screenie from my collada renderer / processor
Posted: October 12, 2009 Filed under: Announcements, Game Development | Tags: collada Leave a comment »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
Posted: October 2, 2009 Filed under: libs | Tags: howto Leave a comment »- Download the binary for windows at http://gforge.inria.fr/frs/?group_id=52
- 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!
How to install Boost
Posted: September 29, 2009 Filed under: libs | Tags: howto 2 Comments »How to get Boost working on windows::
1. Download and extract the .zip/.7z etc from boost website to any folder (lets assume: D:\)
2. Open command prompt and goto that folder (D:\boost_1_39_0)
3. Since, boost does not require building code other than the libraries that it provides, go through the following only if you want to install any of the libraries:
At command prompt:
(I am trying to install filesystem,system)
- bootstrap.bat –with-library=filesystem,system stage
- bjam –with-filesystem variant=debug link=static threading=single,multi –libdir=”D:\Libraries\boost_1_39_0\lib”
(PS: These are the options that I chose, one can choose otherwise, as well. Use bjam –help for more options)
You should now have a folder called stage/lib which would have the processed libraries/dll
(WordPress formatting screwed the text which needs to be put in command prompt. I have made a word doc from which commands can be pasted with appropriate changes made to reflect the directory structure)
How to use Qt 4.3 with Visual Studio 2008 Express
Posted: September 16, 2009 Filed under: libs | Tags: howto 2 Comments »BUILD VC++ VERSION OF QT
1. Download and install qt-sdk-win-opensource-2009.01.exe. Install into the default c:\qt\2009.01. It contains MingGW (the gcc toolset for Windows) and Qt Creator, and pre-built binaries built by GCC. You can use this installation as-is if you want to experiment with Qt Creator.
2. Copy the entire folder of c:\qt\2009.01 to c:\qt\4.5.0-vc. We will be modifying c:\qt\4.5.0-vc to build the libraries with VC++. Both directories can co-exist. Use the c:\qt\2009.01 with Qt Creator, and use c:\qt\4.5.0-vc with Visual Studio. (We will see how to use it in Visual Studio later).
3. Open a (Visual Studio Tools) command prompt and run Configure to target platform win32-msvc2005 (substitute win32-msvc2008 for VC2008):
c:\> cd c:\qt\4.5.0-vc\qt
c:\qt\4.5.0-vc\qt> configure -no-qt3support -platform win32-msvc2008
In the above command-line, change the Configure command-line parameters as desired, but be sure to specify -platform to target the desired Visual Studio toolset. Run Configure with no parameters to see a help screen. Configure generates nmake compatible makefiles to build all the libraries.
PS: You might need to run “setenv” at command prompt if the system cries for not finding the right stuff in the right place.
4. Run “nmake” to build. NOTE: You may need to execute Visual Studio’s VCVARS32.BAT (located in e.g. “C:\Program Files\VS2005\VC\bin”) to setup the environment (such as path) to find the VC++ tools like nmake, etc.
5. Let us set up a couple of environment variables that make life easier for us. To edit environment variables, you need to right click “My Computer > Properties > Advanced > Environment Variables”. Add a new (system) variable QTDIR pointing to your Qt install directory, and edit your PATH to include Qt’s “bin” directory as follows:
Variable Name : Value
QTDIR : c:\qt\4.5.0-vc\qt
Append to path Path >c:\qt\4.5.0-vc\bin
6. Now let’s try to get Qt’s “Hello World” tutorial program running from the command line. Fire up the Visual Studio Command Prompt, and create a file “Hello.cpp” containing the following code in a new directory called “hello”:
#include "QApplication"
#include "QPushButton"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton hello("Hello world");
hello.resize(100, 30);
hello.show();
return app.exec();
}
Now, type the following commands in this new folder:
qmake -project
qmake hello.pro
nmake
You should see hello.exe in the Debug folder.
7. If you wish to use the Visual Studio Express IDE, here’s what you should do.
Fire it up, and go to “Tools > Options > Projects and Solutions > VC++ Directories”. Add “$(QTDIR)\include” to the “Include files”, and “$(QTDIR)\lib” to the “Library files” drop-down lists respectively.
Thats it!
Links:
http://dcsoft.com/community_server/blogs/dcsoft/archive/2009/03/06/how-to-setup-qt-4-5-visual-studio-integration.aspx
http://www.pc-maniac.com/?p=59
http://rajorshi.net/blog/2009/01/using-qt-with-msvc-express-2008/
This worked for me:
</pre>
#include <QtGui/QApplication>
#include <QtGui/QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton hello("Hello ME");
hello.resize(100, 30);
hello.show();
return app.exec();
}
<pre>
Following linker libraries are what I needed:
* QtCore4.lib
* QtGui4.lib
To do so, from project properties:
Configuration Properties –> Linker –> Input –> Additional Dependencies –> add “QtCore4.lib QtGui4.lib”
Enabling super fast build time; all hail pre-compiled header files
Posted: August 25, 2009 Filed under: Uncategorized | Tags: c++ techniques Leave a comment »Recently, I was exploring Boost (the c++ library) and I started out writing a simple program where it would recursively return the files and directories in a given directory. Boost is great, but my biggest rant was: its just too slow when I compile it. It was taking a lot of time for a program as simple as I had written. And, all I was including was:
#include "boost\filesystem.hpp" // includes all needed Boost.Filesystem declarations #include <iostream> // for std::cout #include <string> #include <vector>
Thats all! A quick google search on this, made me realize that this is something that a lot of people despise about Boost. Somebody, then recommended me looking up “Pre-compiled Header files”. Oh man, it worked like a charm and guess what, after my first build, the build time dropped from 0:11 to 0:02 seconds, Nhaaice!
There are some nuances that I am exploring, but am convinced, its a good thing to use in a big project where you are including big and heavy header files like windows.h or STL stuff.
Here is a great article at Fractal eXtreme, that says it all.
Some of the in-general quick tips that I learnt from there: (MS VS express 2008 c++)
- Seeing your build time: In the VS IDE; goto: Tools -> Options -> Projects & Solutions -> VC++ Project Settings -> Build Timing :: Set it to yes
- See the list of header files that get included: goto Project properties -> C++ -> Advanced -> Show Includes :: Set it to yes
Here is my sample code listing:
template <class Type>
vector<Type> CFileUtility::FilesInDirectory(const bfs::path &dirPath, bool recursive)
{
vector<Type> fileList;
if( !exists(dirPath) )
{
throw new exception(string(dirPath.string() + " not found!").c_str()); ;
}
else if( bfs::is_regular_file(dirPath) )
{
throw new exception(string(dirPath.string() + " is a File!").c_str());
}
else
{
bfs::directory_iterator iter(dirPath), iter_end;
for(;iter != iter_end; iter++)
{
if( bfs::is_directory(*iter) )
{
if(recursive)
{
vector<Type> list = FilesInDirectory<Type>(*iter, recursive);
fileList.insert(fileList.end(), list.begin(), list.end() );
}
continue;
}
else
fileList.push_back( iter->string() );
}
}
return fileList;
}
