Category Archives: Box2D

Defining Game State – Scenes

Now that we have a lot of the basic pieces in place to make a simple game, we need to think about how to keep track of game state.  For example, how do you know to start with a start menu?  How can you transition to the actual gameplay?  What if user wants to pause the game or quit?

We do this by defining each one of these game states to be a Scene.  Some examples are:

  • Start menu
  • Settings dialogs
  • Credits scroll
  • Game level
  • Game map
  • Pause menu

Continue reading Defining Game State – Scenes

Sensors in Box2D (or how to make a basic platformer)

After playing around with Box2D, I tried to make a simple platformer. After setting up a static body to represent the ground, and a dynamic box to represent the character, I ran into a problem – how do you know whether your character can jump? Essentially you need to know whether he is standing on the ground. If he is on the ground, and the player presses some button, you can do your jumping physics (set a velocity or apply a force/impulse). One way to approach this problem is to use sensors. Sensors are fixtures that don’t affect the result of an actual collision, but can detect when a collision would have occurred. If you place a sensor under your character’s main area, you can detect when there is something right under him. Here is a diagram:
sensor_diagram
Continue reading Sensors in Box2D (or how to make a basic platformer)

Handling Collisions in Box2D

You can read about how collisions in Box2D work over in this tutorial, but in Moai you will find that a lot of the functions referenced there don’t actually exist.  There is no way to get the full contact list of everything that is colliding through getContactList().  However, Moai does provide one way to respond to collisions – the MOAIBox2DFixture’s setCollisionHandler() function.

Here is an example of how you can call it:

function handler(phase, fixtureA, fixtureB, arbiter) 
  print("we had a collision!")
end

myFixture:setCollisionHandler(handler, MOAIBox2DArbiter.END)

Continue reading Handling Collisions in Box2D

Box2D Basics

Box2D is a simple open source 2D physics engine.  It was written as part of a GDC talk in 2006, and a lot of famous iPhone games like Angry Birds use it.  You can find more information about it over at its website. I also found a great set of tutorials here, which introduce a lot of the concepts behind Box2D.  These tutorials are in C++, but you can get the general idea and apply it to Moai/Lua.  Moai has built in support for Box2D, so you can use it without referencing any additional files.

I’m not going to go too deep about how to use Box2D, but I’ll provide some general guidance to get you started.  In this post I’ll show you enough to demonstrate a simple ball bouncing on a floor.

Continue reading Box2D Basics