Following a body with the camera in Box2D

If you want to make a good game, a good camera movement is necessary.

This time we’ll learn to follow a Box2D object with the camera. Box2D does not have a “camera”, so we will have to move the stage according to body position. This is the same script as Real world catapult using Box2D – cleaner code, I just placed a gradient background to help you seeing how the camera is following the objects.

The main idea is following the catapult until it fires the cannonball, then following the cannonball.

This is the result:

Left and right to move, spacebar to fire

And this is the code:

Download the source code. Next time, smarter camera movement and fully commented code.

  • Quintus


  • Hello mate!

    Could you please send yout e-mail to me? I would like to speak with you about your game partnership. I am interested on that and I would really be pleased if you could help me on that subject.


  • superdean

    i sense a kitten cannon like game in the works

  • Emanuele Feronato

    @superdean: maybe some more realistic…

    @ramon: info[at]

  • Pingback: Emanuele Feronato - italian geek and PROgrammer()

  • AlexRath

    Hey, I had another Idea for the Camera Following Algorithm. It uses an Focus Point and some more Easing for Camera Following.

    Anyway, I zipped the rewritten Version (since I added 2 Helper Classes) and should be available to download here:

  • Emanuele it would be nice if you mentioned which version of the box2d library you are using. Judging from the debug draw’s pink colouring on active objects it would appear that you are using 2.1a.

    I bring this up mainly because I spent most of yesterday pulling my hair out after every single box2d tutorial I used (Even hello worlds) wouldn’t even compile, it turns out that using brand new flex 4 and alpha box2d isn’t going to luck you into too much compatibility.

  • Arindam

    What is this, can’t control the game

  • Arturs

    I’m sorry but how this camera move is achieved exactly, I see that in update function you calculate the offset from world center to stage center and store in x and y values, but these values aren’t used anywhere else, or am I missing something?

    Is it something Actionscript specific? I’m not trying to learn action script, only trying to understand the concept

  • It works perfectly using the classic display list, but no using Starling, how can we make it work using Starling? :)