Book Image

Box2D for Flash Games

Book Image

Box2D for Flash Games

Overview of this book

Physics games are getting more and more popular, and Box2D is the best choice if you are looking for a free, stable and robust library to handle physics. With Box2D you can create every kind of 2D physics game, only coding is not the fun part, but the game itself. "Box2D for Flash Games" will guide you through the process of making a Flash physics game starting from the bare bones and taking you by hand through complex features such as forces, joints and motors. As you are learning, your game will have more and more features, like the physics games you are used to playing. The book analyzes two of the most played physics games, and breaks them down to allow readers to build them from scratch in a step-by-step approach. By the end of the book, you will learn how to create basic primitive bodies as well as complex, compound bodies. Motors will give life to cars, catapults and siege machines firing bullets, while a complete collision management will make your game look even more realistic. If you want to make full Flash games with physics, then Box2D for Flash Games will guide you through the entire process of making a Flash physics game.
Table of Contents (15 chapters)
Box2D for Flash Games
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Your first simulation – a ball falling on the floor


We are starting with an easy task, the simplest of all physics simulations: a ball falling on the floor. Anyway, although it's just another falling ball, being your first simulation this will be quite an achievement.

Let's see what we have in our simulation:

  • A world with a gravity

  • A ball that should react to world forces (such as gravity)

  • A floor that shouldn't react to world forces

  • Some kind of materials, as we expect the ball to bounce on the floor

You are already able to configure a world with gravity, so we are going to start with the creation of the ball.

  1. It doesn't matter if we are creating a sphere or a polygon, the first step to create a body is:

    var bodyDef:b2BodyDef=new b2BodyDef();

    b2BodyDef is the body definition, which will hold all data needed to create our rigid body.

  2. Now it's time to place the body somewhere in the world. As we are working on a 640 x 480 size, we'll place the ball in the top-center position of the stage, let's say...