BaH.Box2D: Functions Types Modinfo Source  

Box2D

Box2D is a 2D rigid body simulation library for games. It can be used to make objects move in believable ways and make the world seem more interactive. From the game's point of view a physics engine is just a system for procedural animation. Rather than paying (or begging) an animator to move your actors around, you can let Sir Isaac Newton do the directing.

BaH.Box2D is a BlitzMax language binding (wrapper) of the Box2D library. The documentation is derived from Box2D's accompanying manual and API guide, by Erin Catto.

Table of Contents

1. Introduction
1.1. Prerequisites
1.2. Core Concepts
2. Hello Box2D
2.1. Creating a World
2.2. Creating a Ground Box
2.3. Creating a Dynamic Body
2.4. Simulating the World (of Box2D)
2.5. Cleanup
2.6. The Examples
3. API Design
3.1. Memory Management
3.2. Factories and Definitions
3.3. Units
3.4. User Data
3.5. Strawman
4. The World
4.1. About
4.2. Creating and Destroying a World
4.3. Using a World
4.3.1. Simulation
4.3.2. Exploring the World
4.3.3. AABB Queries
5. Bodies
5.1. About
5.2. Body Definition
5.2.1. Mass Properties
5.2.2. Position and Angle
5.2.3. Damping
5.2.4. Sleep Parameters
5.2.5. Bullets
5.3. Body Factory
5.4. Using a Body
5.4.1. Mass Data
5.4.2. State Information
5.4.3. Position and Velocity
5.4.4. Forces and Impulses
5.4.5. Coordinate Transformations
5.4.6. Lists
6. Shapes
6.1. About
6.2. The Shape Definition
6.2.1. Friction and Restitution
6.2.2. Density
6.2.3. Filtering
6.2.4. Sensors
6.2.5. Circle Definitions
6.2.6. Polygon Definitions
6.3. Shape Factory
6.4. Using a Shape
7. Joints
7.1. About
7.2. The Joint Definition
7.2.1. Distance Joint
7.2.2. Revolute Joint
7.2.3. Prismatic Joint
7.2.4. Pulley Joint
7.2.5. Gear Joint
7.2.6. Mouse Joint
7.3. Joint Factory
7.4. Using Joints
7.4.1. Using Distance Joints
7.4.2. Using Revolute Joints
7.4.3. Using Prismatic Joints
7.4.4. Using Pulley Joints
7.4.5. Using Gear Joints
7.4.6. Using Mouse Joints
8. Contacts
8.1. About
8.2. Contact Listener
8.3. Contact Filtering
9. Loose Ends
9.1. World Boundary
9.2. Implicit Destruction
10. Settings
10.1. About
10.2. Tolerances
11. Debug Drawing

Chapter 1. Introduction

Table of Contents

1.1. Prerequisites
1.2. Core Concepts

1.1. Prerequisites

In this manual it is assumed you are familiar with basic physics concepts, such as mass, force, torque, and impulses. If not, please first consult the many tutorials provided by Chris Hecker and David Baraff (google these names). You do not need to understand their tutorials in great detail, but they do a good job of laying out the basic concepts that will help you use Box2D.

Wikipedia is also an excellent source of physics and mathematics knowledge. In some ways it is more useful than Google, because it has carefully crafted content.

This is not a prerequisite, but if you are curious about the about the inner workings of Box2D, you can look at these articles .

1.2. Core Concepts

Box2D works with several fundamental objects. We briefly define these objects here and more details are given later in this document.

rigid body

A chunk of matter that is so strong that the distance between any two bits of matter on the chunk is completely constant. They are hard like a diamond. In the following discussion we use body interchangably with rigid body.

shape

A 2D piece of collision geometry that is rigidly attached to a body. Shapes have material properties of friction and restitution.

constraint

A constraint is a physical connection that removes degrees of freedom from bodies. In 2D a body has 3 degrees of freedom. If we take a body and pin it to the wall (like a pendulum) we have constrained the body to the wall. At this point the body can only rotate about the pin, so the constraint has removed 2 degrees of freedom.

contact constraint

A special constraint designed to prevent penetration of rigid bodies and to simulate friction and restitution. You will never create a contact constraint, they are created automatically by Box2D.

joint

This is a contraint used to hold two or more bodies together. Box2D supports these joint types: revolute, prismatic, distance, and more. Joints may support limits and motors .

joint limit

A joint limit restricts the range of motion of a joint. For example, the human elbow only allows a certain range of angles.

joint motor

A joint motor drives the motion of the connected bodies according to the joint's degrees of freedom. For example, you can use a motor to drive the rotation of an elbow.

world

A physics world is a collection of bodies, shapes, and constraints that interact together. Box2D supports the creation of multiple worlds, but this is usually not necessary or desirable.

Chapter 2. Hello Box2D

Table of Contents

2.1. Creating a World
2.2. Creating a Ground Box
2.3. Creating a Dynamic Body
2.4. Simulating the World (of Box2D)
2.5. Cleanup
2.6. The Examples

In the distribution of Box2D is a Hello World project. The program creates a large ground box and a small dynamic box. This code does not contain any graphics, so prepare to be underwelmed. :)

2.1. Creating a World

Every Box2D program begins with the creation of a world object. This is the physics hub that manages memory, objects, and simulation.

To create a world object, first we need to define a bounding box for the world. Box2D uses the bounding box to accelerate collision detection. The size isn't critical, but a better fit will improve performance. It is better to make the box too big than to make it too small.

Local worldAABB:b2AABB = New b2AABB
worldAABB.SetLowerBound(-100.0, -100.0)
worldAABB.SetUpperBound(100.0, 100.0)
		

Caution

The world AABB should always be bigger then the region where your bodies are located. It is better to make the world AABB too big than too small. If a body reaches the boundary of the world AABB it will be frozen and will stop simulating.

Next we define the gravity vector. Yes, you can make gravity go sideways (or you could just rotate your monitor). Also we tell the world to allow bodies to sleep when they come to rest. A sleeping body doesn't require any simulation.

Local gravity:b2Vec2 = New b2Vec2.Create(0.0, -10.0)
Local doSleep:int = true
		

Now we create the world object. Normally you would create the world on the heap and store the pointer in one of your game structures. However, creating the world on the stack works fine in this example.

Local world:b2World = New b2World.Create(worldAABB, gravity, doSleep)
		

So now we have our physics world, let's start adding some stuff to it.

2.2. Creating a Ground Box

Bodies are built using the following steps:

  1. Define a body with a position, damping, etc.

  2. Use the world object to create the body.

  3. Define shapes with geometry, friction, density, etc.

  4. Create shapes on the body.

  5. Optionally adjust the body's mass to match the attached shapes.

For step 1 we create the ground body. For this we need a body definition . With the body definition we specify the initial position of the ground body.

Local groundBodyDef:b2BodyDef = New b2BodyDef
groundBodyDef.SetPositionXY(0.0, -10.0)
		

For step 2 the body definition is passed to the world object to create the ground body. The world object does not keep a reference to the body definition. The ground body is created as a static body. Static bodies don't collide with other static bodies and are immovable. Box2D determines that a body is static when it has zero mass. Bodies have zero mass by default, therefore they are static by default.

Local groundBody:b2Body = world.CreateBody(groundBodyDef)
		

For step 3 we create a ground polygon definition. We use the SetAsBox shortcut to form the ground polygon into a box shape, with the box centered on the origin of the parent body.

Local groundShapeDef:b2PolygonDef = New b2PolygonDef
groundShapeDef.SetAsBox(50.0, 10.0)
		

The SetAsBox function takes the half-width and half-height. So in this case the ground box is 100 units wide (x-axis) and 20 units tall (y-axis). Box2D is tuned for meters, kilograms, and seconds. So you can consider the extents to be in meters. However, it is possible to change unit systems, as discussed later in this document

We finish the ground body in step 4 by creating the ground polygon shape on the ground body.

groundBody.CreateShape(groundShapeDef)
		

Again, Box2D does not keep a reference to the shape or body definitions. It copies the data into the b2Body structure.

Note that every shape must have a parent body, even shapes that are static. However, you can attach all static shapes to a single static body. This need for static bodies is done to make the Box2D code more uniform internally, reducing the number of potential bugs.

You might notice a pattern here. Most Box2D types are prefixed with b2 . This is done to reduce the chance for naming conflicts with your code.

2.3. Creating a Dynamic Body

So now we have a ground body. We can use the same technique to create a dynamic body. The main difference, besides dimensions, is that we must establish the dynamic body's mass properties.

First we create the body using CreateBody .

Local bodyDef:b2BodyDef = new b2BodyDef
bodyDef.SetPositionXY(0.0, 4.0)
Local body:b2Body = world.CreateBody(bodyDef)
		

Next we create and attach a polygon shape. Notice that we set density to 1. The default density is zero. Also, the friction on the shape is set to 0.3. Once the shape is attached, we instruct the body to compute it's mass properties from the attached shapes using the method SetMassFromShapes . This gives you a hint that you can attach more than one shape per body. If the computed mass is zero, then the body becomes truly static. Bodies have a mass of zero by default, that's why we didn't need to call SetMassFromShapes for the ground body.

Local shapeDef:b2PolygonDef = New b2PolygonDef
shapeDef.SetAsBox(1.0, 1.0)
shapeDef.SetDensity(1.0)
shapeDef.SetFriction(0.3)
body.CreateShape(shapeDef)
body.SetMassFromShapes()
		

That's it for initialization. We are now ready to begin simulating.

2.4. Simulating the World (of Box2D)

So we have initialized the ground box and a dynamic box. Now we are ready to set Newton loose to do his thing. We just have a couple more issues to consider.

Box2D uses a bit of numerical code called an integrator . Integrators simulate the physics equations at discrete points of time. This goes along with the traditional game loop where we essentially have a flip book of movement on the screen. So we need to pick a time step for Box2D. Generally physics engines for games like a time step at least as fast as 60Hz or 1/60 seconds. You can get away with larger time steps, but you will have to be more careful about setting up the definitions for your world. We also don't like the time step to change much. So don't tie the time step to your frame rate (unless you really, really have to). Without further ado, here is the time step.

Local timeStep:Float = 1.0 / 60.0
		

In addition to the integrator, Box2D also uses a larger bit of code called a constraint solver. The constraint solver solves all the constraints in the simulation, one at a time. A single constraint can be solved perfectly. However, when we solve one constraint, we slightly disrupt other constraints. To get a good solution, we need to iterate over all constraints a number of times.

There are two phases in the constraint solver: a velocity phase and a position phase. In the velocity phase the solver computes the impulses necessary for the bodies to move correctly. In the position phase the solver adjusts the positions of the bodies to reduce overlap and joint detachment. Each phase has its own iteration count. In addition, the position phase will exit iteraions early if the errors are small.

The suggested iteration count for Box2D is 10 for both velocity and position. You can tune this number to your liking, just keep in mind that this has a trade-off between speed and accuracy. Using fewer iterations increases performance but accuracy suffers. Likewise, using more iterations decreases performance but improves the quality of your simulation. For this simple example, we don't need many iterations. Here are our chosen iteration counts.

Local velocityIterations:Int = 8
Local positionIterations:Int = 1
		

Note that the time step and the iteration count are completely unrelated. An iteration is not a sub-step. One iteration is a single pass over all the constraints withing a time step. You can have multiple passes over the constraints within a single time step.

We are now ready to begin the simulation loop. In your game the simulation loop can be merged with your game loop. In each pass through your game loop you call b2World::Step. Just one call is usually enough, depending on your frame rate and your physics time step.

The Hello World program was designed to be dead simple, so it has no graphical output. Rather that being utterly boring by producing no output, the code prints out the position and rotation of the dynamic body. Yay! Here is the simulation loop that simulates 60 time steps for a total of 1 second of simulated time.

For Local i:Int = 0 Until 60
	world.DoStep(timeStep, velocityIterations, positionIterations)
	Local position:b2Vec2 = body.GetPosition()
	Local angle:Float = body.GetAngle()
	Print position.X() + " " + position.Y() + " " + angle
Next
		

2.5. Cleanup

When a world leaves scope or is deleted by calling delete on a pointer, all the memory reserved for bodies and joints is freed. This is done to make your life easier. However, you will need to nullify any body, shape, or joint pointers you have because they will become invalid.

2.6. The Examples

Once you have conquered the HelloWorld example, you should start looking at Box2D's examples.

The testbed has many examples of Box2D usage in the test cases and the framework itself. I encourage you to explore and tinker with the testbed as you learn Box2D.

Chapter 3. API Design

Table of Contents

3.1. Memory Management
3.2. Factories and Definitions
3.3. Units
3.4. User Data
3.5. Strawman

3.1. Memory Management

A large number of the decisions about the design of Box2D were based on the need for quick and efficient use of memory. In this section I will discuss how and why Box2D allocates memory.

Box2D tends to allocate a large number of small objects (around 50-300 bytes). Using the system heap through malloc or new for small objects is inefficient and can cause fragmentation. Many of these small objects may have a short life span, such as contacts, but can persist for several time steps. So we need an allocator that can efficiently provide heap memory for these objects.

Box2D's solution is to use a small object allocator (SOA). The SOA keeps a number of growable pools of varying sizes. When a request is made for memory, the SOA returns a block of memory that best fits the requested size. When a block is freed, it is returned to the pool. Both of these operations are fast and cause little heap traffic.

Since Box2D uses a SOA, you should never new or malloc a body, shape, or joint. You do have to allocate a b2World. The b2World class provides factories for you to create bodies, shapes, and joints. This allows Box2D to use the SOA and hide the gory details from you. Never, ever, call delete or free on a body, shape, or joint.

While executing a time step, Box2D needs some temporary workspace memory. For this, it uses a stack allocator to avoid per-step heap allocations. You don't need to interact with the stack allocator, but it's good to know it's there.

3.2. Factories and Definitions

As mentioned above, memory management plays a central role in the design of the Box2D API. So when you create a b2Body or a b2Joint , you need to call the factory methods on b2World .

There are creation methods:

Method CreateBody:b2Body(def:b2BodyDef)
Method CreateJoint:b2Joint(def:b2JointDef)
		

And there are corresponding destruction methods:

Method DestroyBody(body:b2Body)
Method DestroyJoint(joint:b2Joint)
		

When you create a body or joint, you need to provide a definition or def for short. These definitions contain all the information needed to build the body or joint. By using this approach we can prevent construction errors, keep the number of function parameters small, provide sensible defaults, and reduce the number of accessors.

Since shapes musted be parented to a body, they are created and destroyed using a factory method on b2Body :

Method CreateShape:b2Shape(def:b2ShapeDef)
Method DestroyShape(shape:b2Shape)
		

Factories do not retain references to the definitions. So you can create and re-use definitions and keep them in temporary resources.

3.3. Units

Box2D works with floating point numbers, so some tolerances have to be used to make Box2D perform well. These tolerance have been tuned to work well with meters-kilogram-second (MKS) units. In particular, Box2D has been tuned to work well with moving objects between 0.1 and 10 meters. So this means objects between soup cans and buses in size should work well.

Being a 2D physics engine it is tempting to use pixels as your units. Unfortunately this will lead to a poor simulation and possibly weird behavior. An object of length 200 pixels would be seen by Box2D as the size of a 45 story building. Imagine trying to simulate the movement of a high-rise building with an engine that is tuned to simulate ragdolls and barrels. It isn't pretty.

Caution

Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors.

3.4. User Data

The b2Shape , b2Body , and b2Joint classes allow you to attach user data as a void pointer. This is handy when you are examining Box2D data structures and you want to determine how they relate to the data structures in your game engine.

For example, it is typical to attach an actor pointer to the rigid body on that actor. This sets up a circular reference. If you have the actor, you can get the body. If you have the body, you can get the actor.

Local actor:GameActor = GameCreateActor()
Local bodyDef:b2BodyDef = new b2BodyDef
bodyDef.SetUserData(actor)
actor.body = box2Dworld.CreateBody(bodyDef)
		

Here are some examples of cases where you would need the user data:

  • Applying damage to an actor using a collision result.

  • Playing a scripted event if the player is inside an axis-aligned box.

  • Accessing a game structure when Box2D notifies you that a joint is going to be destroyed.

Keep in mind that user data is optional and you can put anything in it. However, you should be consistent. For example, if you want to store an actor pointer on one body, you should keep an actor pointer on all bodies. Don't store an actor pointer on one body, and a foo pointer on another body. This will likely lead to a crash if you try to cast an actor pointer into a foo pointer.

3.5. Strawman

If you don't like this API design, that's ok! You have the source code! Seriously, if you have feedback about anything related to Box2D, please leave a comment in the forum .

Chapter 4. The World

Table of Contents

4.1. About
4.2. Creating and Destroying a World
4.3. Using a World
4.3.1. Simulation
4.3.2. Exploring the World
4.3.3. AABB Queries

4.1. About

The b2World class contains the bodies and joints. It manages all aspects of the simulation and allows for asynchronous queries (like AABB queries). Much of your interactions with Box2D will be with a b2World object.

4.2. Creating and Destroying a World

Creating a world is fairly simple. You need to provide a bounding box and a gravity vector.

The axis-aligned bounding box should encapsulate the world. You can improve performance by making the bounding box a bit bigger than your world, say 2x just to be safe. If you have lots of bodies that fall into the abyss, your should detect this and remove the bodies. This will improve performance and prevent floating point overflow.

To create and destory a world you need to use Create and Free .

Local myWorld:b2World = new b2World.Create(aabb, gravity, doSleep);
... do stuff ...
myWorld.Free()
		

Caution

Recall that the world AABB should always be bigger then the region where your bodies are located. If bodies leave the world AABB, then they will be frozen. This is not a bug.

4.3. Using a World

The world class contains factories for creating and destroying bodies and joints. These factories are discussed later in the sections on bodies and joints. There are some other interactions with b2World that I will cover now.

4.3.1. Simulation

The world class is used to drive the simulation. You specify a time step and an iteration count. For example:

Local timeStep:Float = 1.0 / 60.0
Local iterationCount:Int = 10
myWorld.DoStep(timeStep, iterationCount)
			

After the time step you can examine your bodies and joints for information. Most likely you will grab the position off the bodies so that you can update your actors and render them. You can perform the time step anywhere in your game loop, but you should be aware of the order of things. For example, you must create bodies before the time step if you want to get collision results for the new bodies in that frame.

As I discussed above in the HelloWorld tutorial, you should use a fixed time step. By using a larger time step you can improve performance in low frame rate scenarios. But generally you should use a time step no larger than 1/30 seconds. A time step of 1/60 seconds will usually deliver a high quality simulation.

The iteration count controls how many times the constraint solver sweeps over all the contacts and joints in the world. More iterations always yields a better simulation. But don't trade a small time step for a large iteration count. 60Hz and 10 iterations is far better than 30Hz and 20 iterations.

4.3.2. Exploring the World

As mentioned before, the world is a container for bodies and joints. You can grab the body and joint lists off the world and iterate over them. For example, this code wakes up all the bodies in the world:

Local b:b2Body = myWorld.GetBodyList()
While b
	b.WakeUp()
	b = b.GetNext()
Wend
			

Unfortunately life can be more complicated. For example, the following code is broken:

Local b:b2Body = myWorld.GetBodyList()
While b
	Local myActor:GameActor = GameActor(b.GetUserData())
	If myActor.IsDead() Then
		myWorld.DestroyBody(b) ' ERROR: now GetNext returns garbage.
	End If
	b = b.GetNext()
Wend
			

Everything goes ok until a body is destroyed. Once a body is destroyed, its next pointer becomes invalid. So the call to b2Body::GetNext() will return garbage. The solution to this is to copy the next pointer before destroying the body.

Local node:b2Body = myWorld.GetBodyList()
While (node)
	Local b:b2Body = node
	node = node.GetNext()

Local myActor:GameActor = GameActor(b.GetUserData()) If myActor.IsDead() Then myWorld.DestroyBody(b) End If Wend

This safely destroys the current body. However, you may want to call a game function that may destroy multiple bodies. In this case you need to be very careful. The solution is application specific, but for convenience I'll show one method of solving the problem.

Local node:b2Body = myWorld.GetBodyList()
While node
	Local b:b2Body = node
	node = node.GetNext()

Local myActor:GameActor = GameActor(b.GetUserData()) If myActor.IsDead() Then Local otherBodiesDestroyed:Int = GameCrazyBodyDestroyer(b) If otherBodiesDestroyed Then node = myWorld.GetBodyList() End If End If Wend

Obviously to make this work, GameCrazyBodyDestroyer must be honest about what it has destroyed.

4.3.3. AABB Queries

Sometimes you want to determine all the shapes in a region. The b2World class has a fast log(N) method for this using the broad-phase data structure. You provide an AABB in world coordinates and b2World returns an array of all the shapes that potentially intersect the AABB. This is not exact because what the function actually does is return all the shapes whose AABBs intersect the specified AABB. For example, the following code finds all the shapes that potentially intersect a specified AABB and wakes up all of the associated bodies.

Local aabb:b2AABB = new b2AABB
aabb.SetLowerBound(-1.0, -1.0)
aabb.SetUpperBound(1.0, 1.0)
Local k_bufferSize:Int = 10
Local buffer:b2Shape[] = New b2Shape[k_bufferSize]
Local count:Int = myWorld.Query(aabb, buffer)
For Local i:Int = 0 Until count
	buffer[i].GetBody().WakeUp()
Next
			

Chapter 5. Bodies

Table of Contents

5.1. About
5.2. Body Definition
5.2.1. Mass Properties
5.2.2. Position and Angle
5.2.3. Damping
5.2.4. Sleep Parameters
5.2.5. Bullets
5.3. Body Factory
5.4. Using a Body
5.4.1. Mass Data
5.4.2. State Information
5.4.3. Position and Velocity
5.4.4. Forces and Impulses
5.4.5. Coordinate Transformations
5.4.6. Lists

5.1. About

Bodies have position and velocity. You can apply forces, torques, and impulses to bodies. Bodies can be static or dynamic. Static bodies never move and don't collide with other static bodies.

Bodies are the backbone for shapes. Bodies carry shapes and move them around in the world. Bodies are always rigid bodies in Box2D. That means that two shapes attached to the same rigid body never move relative to each other.

You usually keep references to all the bodies you create. This way you can query the body positions to update the positions of your graphical entities. You should also keep body references so you can destroy them when you are done with them.

5.2. Body Definition

Before a body is created you must create a body definition ( b2BodyDef ). You can create a body definition on the stack or build it into your game's data structures. The choice is up to you.

Box2D copies the data out of the body definition, it does not keep a pointer to the body definition. This means you can recycle a body definition to create multiple bodies.

Lets go over some of the key members of the body definition.

5.2.1. Mass Properties

There are a few ways to establish the mass properties for a body.

  1. Set the mass properties explicitly in the body definition.

  2. Set the mass properties explicitly on the body (after it has been created).

  3. Set the mass properties based on the density of the attaced shapes.

In many game scenarios it makes sense to compute mass based on shape densities. This helps to ensure that bodies have reasonable and consistent mass values.

However, other game scenarios may require specific mass values. For example, you may have a mechanism, like a scale that needs precises mass values.

You can explicitly set the mass properties in the body definition as follows:

bodyDef.GetMassData().SetMass(2.0) ' the body's mass in kg
bodyDef.SetCenter(b2Vec2.ZERO)     ' the center of mass in local coordinates
bodyDef.SetRotationalInertia(3.0)  ' the rotational inertia in kg*m^2.
			

The other methods of setting the mass properties are covered elsewhere in this document.

5.2.2. Position and Angle

The body definition gives you the chance to initialize the position of the body on creation. This has better performance than creating the body at the world origin and then moving the body.

A body has two main points of interest. The first point is the body's origin . Shapes and joints are attached relative to the body's origin. The second point of interest is the center of mass . The center of mass is determined from mass distribution of the attached shapes or is explicitly set with b2MassData . Much of Box2D's internal computations use the center of mass position. For example b2Body stores the linear velocity for the center of mass.

When you are building the body definition, you may not know where the center of mass is located. Therefore you specify the position of the body's origin. You may also specify the body's angle in radians, which is not affected by the position of the center of mass. If you later change the mass properties of the body, then the center of mass may move on the body, but the origin position does not change and the attached shapes and joints do not move.

bodyDef.SetPositionXY(0.0, 2.0) ' the body's origin position
bodyDef.SetAngle(45)            ' the body's angle in degrees.
			

5.2.3. Damping

Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact and damping is much cheaper to simulate than friction. However, damping is not a replacement for friction and the two effects should be used together.

Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. I generally do not use linear damping because it makes bodies look floaty .

bodyDef.SetLinearDamping(0.0)
bodyDef.SetAngularDamping(0.01)
			

Damping is approximated for stability and performance. At small damping values the damping effect is mostly independent of the time step. At larger damping values, the damping effect will vary with the time step. This is not an issue if you use a fixed time step (recommended).

5.2.4. Sleep Parameters

What does sleep mean? Well it is expensive to simulate bodies, so the less we have to simulate the better. When a body comes to rest we would like to stop simulating it.

When Box2D determines that a body (or group of bodies) has come to rest, the body enters a sleep state which has very little CPU overhead. If an awake body collides with a sleeping body, then the sleeping body wakes up. Bodies will also wake up if a joint or contact attached to them is destroyed. You can also wake a body manually.

The body definition lets you specify whether a body can sleep and whether a body is created sleeping.

bodyDef.SetAllowSleep(True)
bodyDef.SetIsSleeping(False)
			

5.2.5. Bullets

Game simulation usually generates a sequence of images that are played at some frame rate. In this setting rigid bodies can move by a large amount in one time step. If a physics engine doesn't account for the large motion, you may see some objects incorrectly pass through each other. This effect is called tunneling .

By default, Box2D uses continuous collision detection (CCD) to prevent dynamic bodies from tunneling through static bodies. This is done by sweeping shapes from their old position to their new positions. The engine looks for new collisions during the sweep and computes the time of impact (TOI) for these collisions. Bodies are moved to their first TOI and then simulated to the end of the original time step. This process is repeated as necessary.

Normally CCD is not used between dynamic bodies. This is done to keep performance reasonable. In some game scenarios you need dynamic bodies to use CCD. For example, you may want to shoot a high speed bullet at a thin wall. Without CCD, the bullet my tunnel through the wall.

Fast moving objects in Box2D are called bullets. You should decide what bodies should be bullets based on your game design. If you decide a body should be treated as a bullet, use the following setting.

bodyDef.SetIsBullet(True)

The bullet flag only affects dynamic bodies.

CCD is expensive so you probably don't want all moving bodies to be bullets. So by default Box2D only uses CCD between moving bodies and static bodies. This is an effective approach to prevent bodies from escaping your game world. However, you may have some fast moving bodies that that require CCD all the time.

5.3. Body Factory

Bodies are created and destroyed using a body factory provided by the world class. This lets the world create the body with an efficient allocator and add the body to the world data structure.

Bodies can be dynamic or static depending on the mass properties. Both body types use the same creation and destruction methods.

Local dynamicBody:b2Body = myWorld.CreateBody(bodyDef)
... do stuff ... 
myWorld.DestroyBody(dynamicBody)
dynamicBody = NULL
		

Static bodies do not move under the influence of other bodies. You may manually move static bodies, but you should be careful so that you don't squash dynamic bodies between two or more static bodies. Friction will not work correctly if you move a static body. Static bodies never simulate on their own and they never collide with other static bodies. It is faster to attach several shapes to a static body than to create several static bodies with a single shape on each one. Interally, Box2D sets the mass and inverse mass of static bodies to zero. This makes the math work out so that most algorithms don't need to treat static bodies as a special case.

Box2D does not keep a reference to the body definition or any of the data it holds (except user data references). So you can create temporary body definitions and reuse the same body definitions.

Box2D allows you to avoid destroying bodies by deleting your b2World object, which does all the cleanup work for you. However, you should be mindful to nullify any body references that you keep in your game engine.

When you destroy a body, the attached shapes and joints are automatically destroyed. This has important implications for how you manage shape and joint references. See Section 9.2,

#8220;Implicit Destruction”
			
			for details.
		

Suppose you want to connect a dynamic body to ground with a joint. You'll need to connect the joint to a static body. If you don't have a static body, you can get a shared ground body from your world object. You can also attach static shapes to the ground body.

Local ground:b2Body = myWorld.GetGroundBody()
... build a joint using the ground body ...
		

5.4. Using a Body

After creating a body, there are many operations you can perform on the body. These include setting mass properties, accessing position and velocity, applying forces, and transforming points and vectors.

5.4.1. Mass Data

You can adjust the mass of a body at run-time. This is usually done when you create or destroy shapes on a body. You may want to adjust the mass of the body based on the current shapes.

Method SetMassFromShapes()

You may also want to set the mass properties directly. For example, you may change the shapes, but want to use your own mass formulas.

Method SetMass(massData:b2MassData)
			

The body's mass data is available through the following functions:

Method GetMass:Float()
Method GetInertia:Float()
Method GetLocalCenter:b2Vec2()
			

5.4.2. State Information

There are many aspects to the body's state. You can access this state data efficient through the following functions:

Method IsBullet:Int()
Method SetBullet(flag:Int)

Method IsStatic:Int() Method IsDynamic:Int()

Method IsFrozen:Int()

Method IsSleeping:Int() Method AllowSleeping(flag:Int) Method WakeUp()

The bullet state is described in Section 5.2.5,

#8220;Bullets”
				
				. The frozen state is described in
				
					Section 9.1, 
#8220;World Boundary”
				
.

5.4.3. Position and Velocity

You access the position and rotation of a body. This is common when rendering your associated game actor. You can also set the position, although this is less common since you will normally use Box2D to simulate movement.

Method SetXForm:Int(position:b2Vec2, angle:Float)
Method GetXForm:b2XForm()
Method GetPosition:b2Vec2()
Method GetAngle:Float()
			

You can access the center of mass position in world coordinates. Much of the internal simulation in Box2D uses the center of mass. However, you should normally not need to access it. Instead you will usually work with the body transform.

Method GetWorldCenter:b2Vec2()
			

You can access the linear and angular velocity. The linear velocity is for the center of mass.

Method SetLinearVelocity(v:b2Vec2)
Method GetLinearVelocity:b2Vec2()
Method SetAngularVelocity(omega:Float)
Method GetAngularVelocity:Float()
			

5.4.4. Forces and Impulses

You can apply forces, torques, and impulses to a body. When you apply a force or an impulse, you provide a world point where the load is applied. This often results in a torque about the center of mass.

Method ApplyForce(force:b2Vec2, point:b2Vec2)
Method ApplyTorque(float32 torque:Float)
Method ApplyImpulse(impulse:b2Vec2, point:b2Vec2)
			

Applying a force, torque, or impulse wakes the body. Sometimes this is undesirable. For example, you may be applying a steady force and want to allow the body to sleep to improve performance. In this case you can use the following code.

If Not myBody.IsSleeping() Then
	myBody.ApplyForce(myForce, myPoint)
End If
			

5.4.5. Coordinate Transformations

The body class has some utility functions to help you transform points and vectors between local and world space. If you don't understand these concepts, please read "Essential Mathematics for Games and Interactive Applications" by Jim Van Verth and Lars Bishop. These functions are efficient, so use them with impunity.

Method GetWorldPoint:b2Vec2(localPoint:b2Vec2)
Method GetWorldVector:b2Vec2(localVector:b2Vec2)
Method GetLocalPoint:b2Vec2(worldPoint:b2Vec2)
Method GetLocalVector:b2Vec2(worldVector:b2Vec2)
			

5.4.6. Lists

You can iterate over a body's shapes. This is mainly useful if you need to access the shape's user data.

Local s:b2Shape = body.GetShapeList()
While s
	Local data:MyShapeData = MyShapeData(s.GetUserData())
	... do something with data ...
	s = s.GetNext()
Wend
			

You can similarly iterate over the body's joint list.

Chapter 6. Shapes

Table of Contents

6.1. About
6.2. The Shape Definition
6.2.1. Friction and Restitution
6.2.2. Density
6.2.3. Filtering
6.2.4. Sensors
6.2.5. Circle Definitions
6.2.6. Polygon Definitions
6.3. Shape Factory
6.4. Using a Shape

6.1. About

Shapes are the collision geometry attached to bodies. Shapes are also used to define the mass of a body. This lets you specify the density and let Box2D do the work of computing the mass properties.

Shapes have properties of friction and restitution. Shapes carry collision filtering information to let you prevent collisions between certain game objects.

Shapes are always owned by a body. You can attach multiple shapes to a single body. Shapes are abstract classes so that many types of shapes can be implemented in Box2D. If you are brave, you can implement your own shape type (and collision algorithms).

6.2. The Shape Definition

Shape definitions are used to create shapes. There is common shape data held by b2ShapeDef and specific shape data held by derived classes.

6.2.1. Friction and Restitution

Friction is used to make objects slide along each other realistically. Box2D supports static and dynamic friction, but uses the same parameter for both. Friction is simulated accurately in Box2D and the friction strength is proportional to the normal force (this is called Coulomb friction ). The friction parameter is usually set between 0 and 1. A value of zero turns off friction and a value of one makes the friction strong. When the friction is computed between two shapes, Box2D must combine the friction parameters of the two shapes. This is done with the following formula:

Local friction:Float = Sqr(shape1.GetFriction() * shape2.GetFriction())
			

Restitution is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. Restitution is combined using the following formula.

Local restitution:Float = b2Max(shape1.GetRestitution(), shape2.GetRestitution())
			

When a shape develops multiple contacts, restitution is simulated approximately. This is because Box2D uses an iterative solver. Box2D also uses inelastic collisions when the collision velocity is small. This is done to prevent jitter.

6.2.2. Density

Box2D optionally computes the mass and rotational inertia of bodies using the mass distribution implied by the attached shapes. Specifying mass directly can often lead to poorly tuned simulations. Therefore, the recommended way of specifying body mass is by setting the shape densities and calling b2Body::SetMassFromShape once all the shapes are attached to the body.

6.2.3. Filtering

Collision filtering is a system for preventing collision between shapes. For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with the terrain, but you don't want the character to collide with the bicycle (because they must overlap). Box2D supports such collision filtering using categories and groups.

Box2D supports 16 collision categories. For each shape you can specify which category it belongs to. You also specify what other categories this shape can collide with. For example, you could specify in a multiplayer game that all players don't collide with each other and monsters don't collide with each other, but players and monsters should collide. This is done with masking bits . For example:

playerShapeDef.GetFilter().SetCategoryBits($0002)
monsterShapeDef.GetFilter().SetCategoryBits($0004)
playerShape.GetFilter().SetMaskBits($0004)
monsterShapeDef.GetFilter().SetMaskBits($0002)
			

Collision groups let you specify an integral group index. You can have all shapes with the same group index always collide (positive index) or never collide (negative index). Group indices are usually used for things that are somehow related, like the parts of a bicycle. In the following example, shape1 and shape2 always collide, but shape3 and shape4 never collide.

shape1Def.GetFilter().SetGroupIndex(2)
shape2Def.GetFilter().SetGroupIndex(2)
shape3Def.GetFilter().SetGroupIndex(-8)
shape4Def.GetFilter().SetGroupIndex(-8)
			

Collisions between shapes of different group indices are filtered according the category and mask bits. In other words, group filtering has higher precendence than category filtering.

Note that additional collision filtering occurs in Box2D. Here is a list:

  • A shape on a static body never collides with a shape on another static body.

  • Shapes on the same body never collide with each other.

  • You can optionally enable/disable collision between shapes on bodies connected by a joint.

Sometimes you might need to change collision filtering after a shape has already been created. You can get and set the b2FilterData structure on an existing shape using b2Shape::GetFilterData and b2Shape::SetFilterData . Box2D caches filtering results, so you must manually re-filter a shape using b2World::Refilter .

6.2.4. Sensors

Some times game logic needs to know when two shapes overlap yet there should be no collision response. This is done by using sensors. A sensor is a shape that detects collision but does not produce a response.

You can flag any shape as being a sensor. Sensors may be static or dynamic. Remember that you may have multiple shapes per body and you can have any mix of sensors and solid shapes.

myShapeDef.SetIsSensor(True)
			

6.2.5. Circle Definitions

b2CircleDef extends b2ShapeDef and adds a radius and a local position.

Local def:b2CircleDef = New b2CircleDef
def.SetRadius(1.5)
def.SetLocalPosition(Vec2(1.0, 0.0))
			

6.2.6. Polygon Definitions

b2PolyDef is used to implement convex polygons. They are a bit tricky to use correctly, so please read closely. The maximum vertex count is defined by b2_maxPolyVertices which is currently 8. If you need to use more vertices, you must modify b2_maxPolyVertices in b2Settings.h .

When you build a polygon definition you must specify the number of vertices you will use. The vertices must be specified in counter-clockwise (CCW) order about the z-axis of a right-handed coordinate system. This might turn out to be clockwise on your screen, depending on your coordinate system conventions.

Polygons must be convex . In other words, each vertex must point outwards to some degree. Finally, you must not overlap any vertices. Box2D will automatically close the loop.

Here is an example of a polygon definition of a triangle:

Local triangleDef:b2PolygonDef = New b2PolygonDef
Local vertices:b2Vec2[] = New b2Vec2[3]
vertices[0] = Vec2(-1.0, 0.0)
vertices[1] = Vec2(1.0, 0.0)
vertices[2] = Vec2(0.0, 2.0)
triangleDef.SetVertices(vertices)
			

The vertices are defined in the coordinate system of the parent body. If you need to offset a polygon within the parent body, then just offset all the vertices.

For convenience, there are functions to initialize polygons as boxes. You can have either an axis-aligned box centered at the body origin or an oriented box offset from the body origin.

Local alignedBoxDef:b2PolygonDef = New b2PolygonDef
Local hx:Float = 1.0 ' half-width
Local hy:Float = 2.0 ' half-height
alignedBoxDef.SetAsBox(hx, hy)

Local orientedBoxDef:b2PolygonDef = New b2PolygonDef Local center:b2Vec2 = Vec2(-1.5, 0.0) Local angle:Float = 90 orientedBoxDef.SetAsOrientedBox(hx, hy, center, angle)

6.3. Shape Factory

Shapes are created by initializing a shape definition and then passing the definition to the parent body.

Local circleDef:b2CircleDef = new b2CircleDef
circleDef.SetRadius(3.0)
circleDef.SetDensity(2.5)
Local myShape:b2Shape = myBody.CreateShape(circleDef)
[optionally store shape reference somewhere]
		

This creates the shape and attaches it to the body. You do not need to store the shape pointer since the shape will automatically be destroyed when the parent body is destroyed (see Section 9.2,

#8220;Implicit Destruction”
			
			).
		

After you finish adding shapes to a body, you may want to recompute the mass properties of the body based on the child shapes.

myBody.SetMassFromShapes()
		

This function is expensive, so you should only call it when necessary.

You can destroy a shape on the parent body easily. You may do this to model a breakable object. Otherwise you can just leave the shape alone and let the body destruction take care of destroying the attached shapes.

myBody.DestroyShape(myShape)
		

After removing shapes from a body, you may want to call SetMassFromShapes again.

6.4. Using a Shape

There's not much to say here. You can get a shape's type and its parent body. You can also test a point to see if it is contained within the shape. Look at b2Shape.h for details.

Chapter 7. Joints

Table of Contents

7.1. About
7.2. The Joint Definition
7.2.1. Distance Joint
7.2.2. Revolute Joint
7.2.3. Prismatic Joint
7.2.4. Pulley Joint
7.2.5. Gear Joint
7.2.6. Mouse Joint
7.3. Joint Factory
7.4. Using Joints
7.4.1. Using Distance Joints
7.4.2. Using Revolute Joints
7.4.3. Using Prismatic Joints
7.4.4. Using Pulley Joints
7.4.5. Using Gear Joints
7.4.6. Using Mouse Joints

7.1. About

Joints are used to constrain bodies to the world or to each other. Typical examples in games include ragdolls, teeters, and pulleys. Joints can be combined in many different ways to create interesting motions.

Some joints provide limits so you can control the range of motion. Some joint provide motors which can be used to drive the joint at a prescribed speed until a prescribed force/torque is exceeded.

Joint motors can be used in many ways. You can use motors to control position by specifying a joint velocity that is proportional to the difference between the actual and desired position. You can also use motors to simulate joint friction: set the joint velocity to zero and provide a small, but significant maximum motor force/torque. Then the motor will attempt to keep the joint from moving until the load becomes too strong.

7.2. The Joint Definition

Each joint type has a definition that derives from b2JointDef . All joints are connected between two different bodies. One body may static. If you want to waste memory, then create a joint between two static bodies. :)

You can specify user data for any joint type and you can provide a flag to prevent the attached bodies from colliding with each other. This is actually the default behavior and you must set the collideConnected Boolean to allow collision between to connected bodies.

Many joint definitions require that you provide some geometric data. Often a joint will be defined by anchor points . These are points fixed in the attached bodies. Box2D requires these points to be specified in local coordinates. This way the joint can be specified even when the current body transforms violate the joint constraint --- a common ocurrence when a game is saved and reloaded. Additionally, some joint definitions need to know the default relative angle between the bodies. This is necessary to constraint rotation correctly via joint limits or a fixed relative angle.

Initializing the geometric data can be tedious, so many joints have initialization functions that use the current body transforms to remove much of the work. However, these initialization functions should usually only be used for prototyping. Production code should define the geometry directly. This will make joint behavior more robust.

The rest of the joint definition data depends on the joint type. We cover these now.

7.2.1. Distance Joint

One of the simplest joint is a distance joint which says that the distance between two points on two bodies must be constant. When you specify a distance joint the two bodies should already be in place. Then you specify the two anchor points in world coordinates. The first anchor point is connected to body 1, and the second anchor point is connected to body 2. These points imply the length of the distance constraint.

Here is an example of a distance joint definition. In this case we decide to allow the bodies to collide.

Local jointDef:b2DistanceJointDef = New b2DistanceJointDef
jointDef.Initialize(myBody1, myBody2, worldAnchorOnBody1, worldAnchorOnBody2)
jointDef.SetCollideConnected(True)
			

7.2.2. Revolute Joint

A revolute joint forces two bodies to share a common anchor point, often called a hinge point . The revolute joint has a single degree of freedom: the relative rotation of the two bodies. This is called the joint angle .

To specify a revolute you need to provide two bodies and a single anchor point in world space. The initialization function assumes that the bodies are already in the correct position.

In this example, two bodies are connected by a revolute joint at the first body's center of mass.

Local jointDef:b2RevoluteJointDef = New b2RevoluteJointDef
jointDef.Initialize(myBody1, myBody2, myBody1.GetWorldCenter())
			

The revolute joint angle is positive when body2 rotates CCW about the angle point. Like all angles in Box2D, the revolute angle is measured in radians. By convention the revolute joint angle is zero when the joint is created using Initialize() , regardless of the current rotation of the two bodies.

In some cases you might wish to control the joint angle. For this, the revolute joint can optionally simulate a joint limit and/or a motor.

A joint limit forces the joint angle to remain between an lower and upper bound. The limit will apply as much torque as needed to make this happen. The limit range should include zero, otherwise the joint will lurch when the simulation begins.

A joint motor allows you to specify the joint speed (the time derivative of the angle). The speed can be negative or positive. A motor can have infinite force, but this is usually not desirable. Have you ever heard the expression:

Caution

"What happens when an irresistible force meets an immovable object?"

I can tell you it's not pretty. So you can provide a maximum torque for the joint motor. The joint motor will maintain the specified speed unless the required torque exceeds the specified maximum. When the maximum torque is exceeded, the joint will slow down and can even reverse.

You can use a joint motor to simulate joint friction. Just set the joint speed to zero, and set the maximum torque to some small, but significant value. The motor will try to prevent the joint from rotating, but will yield to a significant load.

Here's a revision of the revolute joint definition above; this time the joint has a limit and a motor enabled. The motor is setup to simulate joint friction.

Local jointDef:b2RevoluteJointDef = New b2RevoluteJointDef
jointDef.Initialize(body1, body2, myBody1.GetWorldCenter())
jointDef.SetLowerAngle(-90)
jointDef.SetUpperAngle(45)
jointDef.EnableLimit(True)
jointDef.SetMaxMotorTorque(10.0)
jointDef.SetMotorSpeed(0.0)
jointDef.EnableMotor(True)
			

7.2.3. Prismatic Joint

A prismatic joint allows for relative translation of two bodies along a specified axis. A prismatic joint prevents relative rotation. Therefore, a prismatic joint has a single degree of freedom.

The prismatic joint definition is similar to the revolute joint description; just substitute translation for angle and force for torque. Using this analogy provides an example prismatic joint definition with a joint limit and a friction motor:

Local jointDef:b2PrismaticJointDef = new b2PrismaticJointDef
Local worldAxis:b2Vec2 = new b2Vec2.Create(1.0, 0.0)
jointDef.Initialize(myBody1, myBody2, myBody1.GetWorldCenter(), worldAxis)
jointDef.SetLowerTranslation(-5.0)
jointDef.SetUpperTranslation(2.5)
jointDef.SetEnableLimit(True)
jointDef.SetMotorForce(1.0)
jointDef.SetMotorSpeed(0.0)
jointDef.EnableMotor(True)
			

The revolute joint has an implicit axis coming out of the screen. The prismatic joint needs an explicit axis parallel to the screen. This axis is fixed in the two bodies and follows their motion.

Like the revolute joint, the prismatic joint translation is zero when the joint is created using Initialize() . So be sure zero is between your lower and upper translation limits.

7.2.4. Pulley Joint

A pulley is used to create an idealized pulley. The pulley connects two bodies to ground and to each other. As one body goes up, the other goes down. The total length of the pulley rope is conserved according to the initial configuration.

length1 + length2 = constant
			

You can supply a ratio that simulates a block and tackle . This causes one side of the pulley to extend faster than the other. At the same time the constraint force is smaller on one side than the other. You can use this to create mechanical leverage.

length1 + ratio * length2 = constant
			

For example, if the ratio is 2, then length1 will vary at twice the rate of length2. Also the force in the rope attached to body1 will have half the constraint force as the rope attached to body2.

Pulleys can be troublesome when one side is fully extended. The rope on the other side will have zero length. At this point the constraint equations become singular (bad). Therefore the pulley joint constrains the maximum length that either side can attain. Also, you may want to control the maximum lengths for gameplay reasons. So the maximum lengths improve stability and give you more control.

Here is an example pulley definition:

Local anchor1:b2Vec2 = myBody1.GetWorldCenter()
Local anchor2:b2Vec2 = myBody2.GetWorldCenter()
Local groundAnchor1:b2Vec2 = new b2Vec2.Create(p1.X(), p1.Y() + 10.0)
Local groundAnchor2:b2Vec2 = new b2Vec2.Create(p2.X(), p2.Y() + 12.0)
Local ratio:Float = 1.0
Local jointDef:b2PulleyJointDef = new b2PulleyJointDef
jointDef.Initialize(myBody1, myBody2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio)
jointDef.SetMaxLength1(18.0)
jointDef.SetMaxLength2(20.0)
			

7.2.5. Gear Joint

If you want to create a sophisticated mechanical contraption you might want to use a gears. In principle you can create gears in Box2D by using compound shapes to model gear teeth. This is not very efficient and might be tedious to author. You also have to be careful to line up the gears so the teeth mesh smoothly. Box2D has a simpler method of creating gears: the gear joint .

The gear joint requires the you have two bodies connected to ground by a revolute or prismatic joint. You can use any combination of those joint types. Also, Box2D requires that the revolute and prismatic joints were created with the ground as body1.

Like the pulley ratio, you can specify a gear ratio. However, in this case the gear ratio can be negative. Also keep in mind that when one joint is a revolute joint (angular) and the other joint is prismatic (translation), then the gear ratio with have units of length or one over length.

coordinate1 + ratio * coordinate2 = constant
			

Here is an example gear joint:

Local jointDef:b2GearJointDef = new b2GearJointDef
jointDef.SetBody1(myBody1)
jointDef.SetBody2(myBody2)
jointDef.SetJoint1(myRevoluteJoint)
jointDef.SetJoint2(myPrismaticJoint)
jointDef.SetRatio(2.0 * Pi / myLength)
			

Note that the gear joint depends on two other joints. This creates a fragile situation. What happens if those joints are deleted?

Caution

Always delete gear joints before the revolute/prismatic joints on the gears. Otherwise your code will crash in a bad way due to the orphaned joint references in the gear joint. You should also delete the gear joint before you delete any of the bodies involved.

7.2.6. Mouse Joint

The mouse joint is used in the examples to manipulate bodies with the mouse.

7.3. Joint Factory

Joints are created and destroyed using the world factory methods. This brings up an old issue:

Caution

You must create and destroy bodies and joints using the create and destroy methods of the b2World class.

Here's an example of the lifetime of a revolute joint:

Local jointDef:b2RevoluteJointDef = new b2RevoluteJointDef
jointDef.SetBody1(myBody1)
jointDef.SetBody2(myBody2)
jointDef.SetAnchorPoint(myBody1.GetCenterPosition())
Local joint:b2RevoluteJoint = myWorld.CreateJoint(jointDef)
... do stuff ...
myWorld.DestroyJoint(joint)
joint = Null
		

It is always good to nullify your pointer after they are destroyed. This will make the program crash in a controlled manner if you try to reuse the pointer.

The lifetime of a joint is not simple. Heed this warning well:

Caution

Joints are destroyed when an attached body is destroyed.

This precaution is not always necessary. You may organize your game engine so that joints are always destroyed before the attached bodies. In this case you don't need to implement the listener class. See Section 9.2, "e;Implicit Destruction"e; for details.

7.4. Using Joints

Many simulations create the joints and don't access them again until they are detroyed. However, there is a lot of useful data contained in joints that you can use to create a rich simulation.

First of all, you can get the bodies, anchor points, and user data from a joint.

Method GetBody1:b2Body()
Method GetBody2:b2Body()
Method GetAnchor1:b2Vec2()
Method GetAnchor2:b2Vec2()
Method GetUserData:Object()
		

All joints have a reaction force and torque. This the reaction force applied to body 2 at the anchor point. You can use reaction forces to break joints or trigger other game events. These functions may do some computations, so don't call them if you don't need the result.

Method GetReactionForce:b2Vec2()
Method GetReactionTorque:Float()
		

7.4.1. Using Distance Joints

Distance joints don't have motors or limits, so there are no extra runtime methods for distance joints.

7.4.2. Using Revolute Joints

You can access a revolute joint's angle, speed, and motor torque.

Method GetJointAngle:Float()
Method GetJointSpeed:Float()
Method GetMotorTorque:Float()
			

You also update the motor parameters each step.

Method SetMotorSpeed(speed:Float)
Method SetMaxMotorTorque(torque:Float)
			

Joint motors have some interesting abilities. You can update the joint speed every time step so you can make the joint move back-and-forth like a sine-wave or according to whatever function you want.

... Game Loop Begin ...
myJoint.SetMotorSpeed(Cos(0.5 * time))
 ... Game Loop End ...
			

You can also use joint motors to track a desired joint angle. For example:

... Game Loop Begin ...
Local angleError:Float = myJoint.GetJointAngle() - angleTarget
Local gain:Float = 0.1
myJoint.SetMotorSpeed(-gain * angleError)
... Game Loop End ...
			

Generally your gain parameter should not be too large. Otherwise your joint may become unstable.

7.4.3. Using Prismatic Joints

Using a prismatic joint is similar to using a revolute joint. Here are the relevant member functions:

Method GetJointTranslation:Float()
Method GetJointSpeed:Float()
Method GetMotorForce:Float()
Method SetMotorSpeed(speed:Float)
Method SetMotorForce(force:Float)
			

7.4.4. Using Pulley Joints

Pully joints provide the current lengths.

Method GetLength1:Float()
Method GetLength2:Float()
			

7.4.5. Using Gear Joints

Gear joints don't provide any information beyond the functions defined in b2Joint .

7.4.6. Using Mouse Joints

The mouse joint is able to manipulate the attached body by updating the target point each time step.

Chapter 8. Contacts

Table of Contents

8.1. About
8.2. Contact Listener
8.3. Contact Filtering

8.1. About

Contacts are objects created by Box2D to manage collision between shapes. There are different kinds of contacts, derived from b2Contact , for managing contact between different kinds of shapes. For example there is a contact class for managing polygon-polygon collision and another contact class for managing circle-circle collision. This is normally not important to you, I just thought you might like to know.

Here is some terminlogy associated with contacts. This terminology is particular to Box2D, but you might find similar terminology in other physics engines.

contact point

A contact point is a point where two shapes touch. In reality objects may touch over regions when surfaces touch. Box2D approximates contact with a small number of points.

contact normal

A contact normal is a unit vector that points from shape1 to shape2.

contact separation

Separation is the opposite of penetration. Separation is negative when shapes overlap. It is possible that future versions of Box2D will create contact points with positive separation, so you may want to check the sign when contact points are reported.

normal force

Box2D use an iterative contact solver and stores the results with the contact points. You can safely use the normal force to guage the collision intensity. For example, you can use the force to trigger breakables or to play collision sounds.

tangent force

The tangent force is the contact solver's estimate of the friction force.

contact ids

Box2D tries to re-use the contact force results from a time step as the initial guess for the next time step. Box2D uses contact ids to match contact points across time steps. The ids contain geometric features indices that help to distinguish one contact point from another.

Contacts are created when two shape's AABBs overlap. Sometimes collision filtering will prevent the creation of contacts. Box2D sometimes needs to create a contact even though the collision is filtered. In this case it uses a b2NullContact that prevents collision from occuring. Contacts are destroyed with the AABBs cease to overlap.

So you might gather that there may be contacts created for shapes that are not touching (just their AABBs). Well, this is correct. It's a "chicken or egg" problem. We don't know if we need a contact object until one is created to analyze the collision. We could delete the contact right away if the shapes are not touching, or we can just wait until the AABBS stop overlapping. Box2D takes the latter approach.

8.2. Contact Listener

You can receive contact data by implementing b2ContactListener . This listener reports a contact point when it is created, when it persists for more than one time step, and when it is destroyed. Keep in mind that two shapes may have multiple contact points.

Type MyContactListener Extends b2ContactListener

Method Add(point:b2ContactPoint) ' handle add point End Method Method Persist(point:b2ContactPoint) ' handle persist point End Method Method Remove(point:b2ContactPoint) ' handle remove point End Method Method Result(point:b2ContactResult) ' handle results End Method

End Type

Caution

Do not keep a reference to the contact points returned to b2ContactListener . Instead make a deep copy of the contact point data into your own buffer. The example below shows one way of doing this.

Continuous physics uses sub-stepping, so a contact point may be added and removed within the same time step. This is normally not a problem, but your code should handle this gracefully.

Contact points are reported immediately when they are added, persisted, or removed. This occurs before the solver is called, so the b2ContactPoint object does not contain the computed impulse. However, the relative velocity at the contact point is provided so that you can estimated the contact impulse. If you implement the Result listener function, you will receive b2ContactResult objects for solid contact points after the solver has been called. These result structures contain the sub-step impulses. Again, due to continuous physics you may receive multiple results per contact point per b2World::DoStep .

It is tempting to implement game logic that alters the physics world inside a contact callback. For example, you may have a collision that applies damage and try to destroy the associated actor and its rigid body. However, Box2D does not allow you to alter the physics world inside a callback because you might destroy objects that Box2D is currently processing, leading to orphaned references.

The recommended practice for processing contact points is to buffer all contact points that you care about and process them after the time step. You should always process the contact points immediately after the time step, otherwise some other client code might alter the physics world, invalidating the contact buffer. When you process the contact point buffer you can alter the physics world, but you still need to be careful that you don't orphan references stored in the contact point buffer. The testbed has example contact point processing that is safe from orphaned references.

This code from the CollisionProcessing test shows how to handle orphaned bodies when processing the contact buffer. Here is an excerpt. Be sure to read the comments in the listing. This code assumes that all contact points have been buffered in the b2ContactPoint array m_points .

' We are going to destroy some bodies according to contact
' points. We must buffer the bodies that should be destroyed
' because they may belong to multiple contact points.
Local k_maxNuke:Int = 6
Local nuke:b2Body[] = new b2Body[k_maxNuke]
Local nukeCount:Int = 0

' Traverse the contact buffer. Destroy bodies that ' are touching heavier bodies. For Local i:Int = 0 Until m_pointCount

Local point:ContactPoint = m_points[i] Local body1:b2Body = point.GetShape1().GetBody() Local body2:b2Body = point.GetShape2().GetBody() Local mass1:Float = body1.GetMass() Local mass2:Float = body2.GetMass() If mass1 > 0.0 And mass2 > 0.0 Then If mass2 > mass1 Then nuke[nukeCount] = body1 Else nuke[nukeCount] = body2 End If nukeCount:+ 1 If nukeCount = k_maxNuke Then Exit End If Next

' Sort the nuke array to group duplicates. 'std::sort(nuke, nuke + nukeCount); .. .TODO

' Destroy the bodies, skipping duplicates. Local i:Int = 0 While i < nukeCount Local b:b2Body = nuke[i] i:+ 1 While i < nukeCount And nuke[i] = b i:+ 1 Wend

m_world.DestroyBody(b) Wend

8.3. Contact Filtering

Often in a game you don't want all objects to collide. For example, you may want to create a door that only certain characters can pass through. This is called contact filtering, because some interactions are filtered out .

Box2D allows you to achieve custom contact filtering by implementing a b2ContactFilter class. This class requires you to implement a ShouldCollide method that receives two b2Shape references. Your method returns true if the shapes should collide.

The default implementation of ShouldCollide uses the b2FilterData defined in Chapter 6, Shapes .

Method ShouldCollide:Int(shape1:b2Shape, shape2:b2Shape)

Local filter1:b2FilterData = shape1.GetFilterData() Local filter2:b2FilterData = shape2.GetFilterData()

If filter1.GetGroupIndex() = filter2.GetGroupIndex() And filter1.GetGroupIndex() <> 0 Then return filter1.GetGroupIndex() < $7FFF End If

Local collide:Int = (filter1.GetMaskBits() & filter2.GetCategoryBits()) <> 0 And .. (filter1.GetCategoryBits() & filter2.GetMaskBits()) <> 0 return collide End Method

Chapter 9. Loose Ends

Table of Contents

9.1. World Boundary
9.2. Implicit Destruction

9.1. World Boundary

You can implement a b2BoundaryListener that allows b2World to inform you when a body has gone outside the world AABB. When you get the callback, you shouldn't try to delete the body, instead you should mark the parent actor for deletion or error handling. After the physics time step, you should handle the event.

Type MyBoundaryListener Extends b2BoundaryListener

Method Violation(body:b2Body) Local myActor:MyActor = MyActor(body.GetUserData()) myActor.MarkForErrorHandling() End Method

End Type

You can then register an instance of your boundary listener with your world object. You should do this during world initialization.

myWorld.SetBoundaryListener(myBoundaryListener)
		

9.2. Implicit Destruction

Box2D doesn't use reference counting. So if you destroy a body it is really gone. Accessing a pointer to a destroyed body has undefined behavior. In other words, your program will likely crash and burn. To help fix these problems, the debug build memory manager fills destroyed entities with FDFDFDFD . This can help find problems more easily in some cases.

If you destroy a Box2D entity, it is up to you to make sure you remove all references to the destroyed object. This is easy if you only have a single reference to the entity. If you have multiple references, you might consider implementing a handle class to wrap the raw pointer.

Often when using Box2D you will create and destroy many bodies, shapes, and joints. Managing these entities is somewhat automated by Box2D. If you destroy a body then all associated shapes and joints are automatically destroyed. This is called implicit destruction .

When you destroy a body, all its attached shapes, joints, and contacts are destroyed. This is called implicit destruction . Any body connected to one of those joints and/or contacts is woken. This process is usually convenient. However, you must be aware of one crucial issue:

Caution

When a body is destroyed, all shapes and joints attached to the body are automatically destroyed. You must nullify any references you have to those shapes and joints. Otherwise, your program will die horribly if you try to access or destroy those shapes or joints later.

To help you nullify your joint references, Box2D provides a listener class named b2WorldListener that you can implement and provide to your world object. Then the world object will notify you when a joint is going to be implicity destroyed.

Implicit destruction is a great convenience in many cases. It can also make your program fall apart. You may store references to shapes and joints somewhere in your code. These references become orphaned when an associated body is destroyed. The situation becomes worse when you consider that joints are often created by a part of the code unrelated to management of the associated body. For example, the testbed creates a b2MouseJoint for interactive manipulation of bodies on the screen.

Box2D provides a callback mechanism to inform your application when implicit destruction occurs. This gives your application a chance to nullify the orphaned pointers. This callback mechanism is described later in this manual.

You can implement a b2DestructionListener that allows b2World to inform you when a shape or joint is implicitly destroyed because an associated body was destroyed. This will help prevent your code from accessing orphaned pointers.

Type MyDestructionListener Extends b2DestructionListener

Method SayGoodbye(joint:b2Joint) ' remove all references to joint. End Method

End Type

You can then register an instance of your destruction listener with your world object. You should do this during world initialization.

myWorld.SetDestructionListener(myDestructionListener)
		

Chapter 10. Settings

Table of Contents

10.1. About
10.2. Tolerances

10.1. About

There are two source files included in Box2D that are supplied specifically for user customization. These are b2Settings.h and b2Settings.cpp .

Box2D works with floating point numbers, so some tolerances have to be used to make Box2D perform well.

10.2. Tolerances

There are many tolerances settings that depend on using MKS units. See Section 3.3, “Units” for a deeper explanation of the unit system. See the doxygen docs for explanation of the individual tolerances.

Chapter 11. Debug Drawing

You can implement the b2DebugDraw class to get detailed drawing of the physics world. Here are the available entities:

This the preferred method of drawing these physics entities, rather than accessing the data directly. The reason is that much of the necessary data is internal and subject to change.

The testbed draws physics entities using the debug draw facility and the contact listener, so it serves as the primary example of how to implement debug drawing as well as how to draw contact points.

Functions Summary

b2Cross Perform the cross product on a vector and a scalar.
b2CrossF Perform the cross product on a scalar and a vector.
b2Dot Peform the dot product on two vectors.
b2Mul Multiply a matrix times a vector.
b2MulF  
b2MulT Multiply a matrix transpose times a vector.
b2MulTF  
Vec2 Convenience function for creating a b2Vec2 object.

Types Summary

b2AABB An axis aligned bounding box.
b2Body Bodies are the backbone for shapes.
b2BodyDef A body definition holds all the data needed to construct a rigid body.
b2BoundaryListener Use this type for when a body's shape passes outside of the world boundary.
b2BuoyancyController Calculates buoyancy forces for fluids in the form of a half plane.
b2BuoyancyControllerDef Used to build buoyancy controllers.
b2CircleDef Used to build circle shapes.
b2CircleShape A circle shape.
b2Color Color for debug drawing.
b2ConstantAccelController Applies a force every frame.
b2ConstantAccelControllerDef Used to build constant acceleration controllers.
b2ConstantForceController Applies a force every frame.
b2ConstantForceControllerDef Used to build constant force controllers.
b2Contact This type manages contact between two shapes.
b2ContactFilter Implement this type and override ShouldCollide() to provide collision filtering.
b2ContactListener Implement this type to get collision results.
b2ContactPoint This type is used to report contact points.
b2ContactResult This type is used to report contact point results.
b2Controller Base type for controllers.
b2ControllerEdge A controller edge is used to connect bodies and controllers together in a bipartite graph.
b2DebugDraw Implement and register this type with a b2World to provide debug drawing of physics entities in your game.
b2DestructionListener Joints and shapes are destroyed when their associated body is destroyed.
b2DistanceJoint A distance joint constrains two points on two bodies to remain at a fixed distance from each other.
b2DistanceJointDef Distance joint definition.
b2EdgeChainDef  
b2EdgeShape  
b2FilterData This holds contact filtering data.
b2GearJoint A gear joint is used to connect two joints together.
b2GearJointDef Gear joint definition.
b2GravityController Applies simplified gravity between every pair of bodies.
b2GravityControllerDef Used to build gravity controllers.
b2Joint The base joint type.
b2JointDef Joint definitions are used to construct joints.
b2JointEdge A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge.
b2LineJoint A line joint.
b2LineJointDef Line joint definition.
b2MassData Holds the mass data computed for a shape.
b2Mat22 A 2-by-2 matrix.
b2MouseJoint A mouse joint is used to make a point on a body track a specified world point.
b2MouseJointDef Mouse joint definition.
b2OBB An oriented bounding box.
b2PolygonDef Convex polygon.
b2PolygonShape A convex polygon.
b2PrismaticJoint  
b2PrismaticJointDef Prismatic joint definition.
b2PulleyJoint The pulley joint is connected to two bodies and two fixed ground points.
b2PulleyJointDef Pulley joint definition.
b2RevoluteJoint A revolute joint constrains to bodies to share a common point while they are free to rotate about the point.
b2RevoluteJointDef Revolute joint definition.
b2Segment A line segment.
b2Shape A shape is used for collision detection.
b2ShapeDef A shape definition is used to construct a shape.
b2TensorDampingController Applies top down linear damping to the controlled bodies.
b2TensorDampingControllerDef Used to build tensor damping controllers.
b2Vec2 A 2D column vector.
b2World The world type manages all physics entities, dynamic simulation, and asynchronous queries.
b2XForm A transform contains translation and rotation.

Functions

Function b2Cross:b2Vec2(a:b2Vec2, s:Float)
DescriptionPerform the cross product on a vector and a scalar.
InformationIn 2D this produces a vector.

Function b2CrossF:b2Vec2(s:Float, a:b2Vec2)
DescriptionPerform the cross product on a scalar and a vector.
InformationIn 2D this produces a vector.

Function b2Dot:Float(a:b2Vec2, b:b2Vec2)
DescriptionPeform the dot product on two vectors.

Function b2Mul:b2Vec2(A:b2Mat22, v:b2Vec2)
DescriptionMultiply a matrix times a vector.
InformationIf a rotation matrix is provided, then this transforms the vector from one frame to another.

Function b2MulF:b2Vec2(T:b2XForm, v:b2Vec2)

Function b2MulT:b2Vec2(A:b2Mat22, v:b2Vec2)
DescriptionMultiply a matrix transpose times a vector.
InformationIf a rotation matrix is provided, then this transforms the vector from one frame to another (inverse transform).

Function b2MulTF:b2Vec2(T:b2XForm, v:b2Vec2)

Function Vec2:b2Vec2(x:Float, y:Float)
DescriptionConvenience function for creating a b2Vec2 object.

Types

Type b2AABB
DescriptionAn axis aligned bounding box.
Methods Summary
Create Creates a new AABB.
IsValid Verify that the bounds are sorted.
SetLowerBound Sets the lower vertex.
SetUpperBound Sets the upper vertex.
Functions Summary
CreateAABB Creates a new AABB.
Method Create:b2AABB(lowerBound:b2Vec2 = Null, upperBound:b2Vec2 = Null)
DescriptionCreates a new AABB.
Method IsValid:Int()
DescriptionVerify that the bounds are sorted.
Method SetLowerBound(lowerBound:b2Vec2)
DescriptionSets the lower vertex.
Method SetUpperBound(upperBound:b2Vec2)
DescriptionSets the upper vertex.
Function CreateAABB:b2AABB(lowerBound:b2Vec2 = Null, upperBound:b2Vec2 = Null)
DescriptionCreates a new AABB.

Type b2Body
DescriptionBodies are the backbone for shapes.
InformationBodies carry shapes and move them around in the world. Bodies are always rigid bodies in Box2D. That means that two shapes attached to the same rigid body never move relative to each other.

Bodies have position and velocity. You can apply forces, torques, and impulses to bodies. Bodies can be static or dynamic. Static bodies never move and don't collide with other static bodies.

Methods Summary
AllowSleeping You can disable sleeping on this body.
ApplyForce Apply a force at a world point.
ApplyImpulse Apply an impulse at a point.
ApplyTorque Apply a torque.
CreateShape Creates a shape and attach it to this body.
DestroyShape Destroy a shape.
GetAngle Get the angle in degrees.
GetAngularVelocity Get the angular velocity.
GetInertia Get the central rotational inertia of the body.
GetJointList Get the list of all joints attached to this body.
GetLinearVelocity Get the linear velocity of the center of mass.
GetLocalCenter Get the Local position of the center of mass.
GetLocalPoint Gets a local point relative to the body's origin given a world point.
GetLocalVector Gets a local vector given a world vector.
GetMass Get the total mass of the body.
GetNext Get the next body in the world's body list.
GetPosition Get the world body origin position.
GetShapeList Get the list of all shapes attached to this body.
GetUserData Get the user data pointer that was provided in the body definition.
GetWorld Get the parent world of this body.
GetWorldCenter Get the world position of the center of mass.
GetWorldPoint Get the world coordinates of a point given the local coordinates.
GetWorldVector Get the world coordinates of a vector given the local coordinates.
GetXForm Get the body transform for the body's origin.
IsBullet Is this body treated like a bullet for continuous collision detection?
IsDynamic Is this body dynamic (movable)?
IsFrozen Is this body frozen?
IsSleeping Is this body sleeping (not simulating).
IsStatic Is this body static (immovable)?
PutToSleep Put this body to sleep so it will stop simulating.
SetAngularVelocity Set the angular velocity.
SetBullet Should this body be treated like a bullet for continuous collision detection?
SetLinearVelocity Set the linear velocity of the center of mass.
SetMass Set the mass properties.
SetMassFromShapes Compute the mass properties from the attached shapes.
SetXForm Set the position of the body's origin and rotation (degrees).
WakeUp Wake up this body so it will begin simulating.
Method AllowSleeping(flag:Int)
DescriptionYou can disable sleeping on this body.
Method ApplyForce(force:b2Vec2, point:b2Vec2)
DescriptionApply a force at a world point.
InformationIf the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This wakes up the body.

Parameters:

  • force : the world force vector, usually in Newtons (N).
  • point : the world position of the point of application.

Method ApplyImpulse(impulse:b2Vec2, point:b2Vec2)
DescriptionApply an impulse at a point.
InformationThis immediately modifies the velocity. It also modifies the angular velocity If the point of application is not at the center of mass. This wakes up the body.

Parameters:

  • impulse : the world impulse vector, usually in N-seconds Or kg-m/s.
  • point : the world position of the point of application.

Method ApplyTorque(torque:Float)
DescriptionApply a torque.
InformationThis affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up the body.

Parameters:

  • torque : about the z-axis (out of the screen), usually in N-m.

Method CreateShape:b2Shape(def:b2ShapeDef)
DescriptionCreates a shape and attach it to this body.
InformationWarning: This method is locked during callbacks.

Parameters:

  • def : the shape definition.

Method DestroyShape(shape:b2Shape)
DescriptionDestroy a shape.
InformationThis removes the shape from the broad-phase and therefore destroys any contacts associated with this shape. All shapes attached to a body are implicitly destroyed when the body is destroyed.

Warning: This method is locked during callbacks.

Method GetAngle:Float()
ReturnsThe current world rotation angle in degrees.
DescriptionGet the angle in degrees.
Method GetAngularVelocity:Float()
ReturnsThe angular velocity in degrees/Second.
DescriptionGet the angular velocity.
Method GetInertia:Float()
ReturnsThe rotational inertia, usually in kg-m^2.
DescriptionGet the central rotational inertia of the body.
Method GetJointList:b2JointEdge()
DescriptionGet the list of all joints attached to this body.
Method GetLinearVelocity:b2Vec2()
ReturnsThe linear velocity of the center of mass.
DescriptionGet the linear velocity of the center of mass.
Method GetLocalCenter:b2Vec2()
DescriptionGet the Local position of the center of mass.
Method GetLocalPoint:b2Vec2(worldPoint:b2Vec2)
ReturnsThe corresponding local point relative to the body's origin.
DescriptionGets a local point relative to the body's origin given a world point.
InformationParameters:
  • worldPoint : a point in world coordinates.
Method GetLocalVector:b2Vec2(worldVector:b2Vec2)
ReturnsThe corresponding local vector.
DescriptionGets a local vector given a world vector.
InformationParameters:
  • worldVector : a vector in world coordinates.
Method GetMass:Float()
ReturnsThe mass, usually in kilograms (kg).
DescriptionGet the total mass of the body.
Method GetNext:b2Body()
DescriptionGet the next body in the world's body list.
Method GetPosition:b2Vec2()
DescriptionGet the world body origin position.
Method GetShapeList:b2Shape()
DescriptionGet the list of all shapes attached to this body.
Method GetUserData:Object()
DescriptionGet the user data pointer that was provided in the body definition.
Method GetWorld:b2World()
DescriptionGet the parent world of this body.
Method GetWorldCenter:b2Vec2()
DescriptionGet the world position of the center of mass.
Method GetWorldPoint:b2Vec2(localPoint:b2Vec2)
ReturnsThe same point expressed in world coordinates.
DescriptionGet the world coordinates of a point given the local coordinates.
InformationParameters:
  • localPoint : a point on the body measured relative the the body's origin.
Method GetWorldVector:b2Vec2(localVector:b2Vec2)
ReturnsThe same vector expressed in world coordinates.
DescriptionGet the world coordinates of a vector given the local coordinates.
InformationParameters:
  • localVector : a vector fixed in the body.
Method GetXForm:b2XForm()
DescriptionGet the body transform for the body's origin.
Method IsBullet:Int()
DescriptionIs this body treated like a bullet for continuous collision detection?
Method IsDynamic:Int()
DescriptionIs this body dynamic (movable)?
Method IsFrozen:Int()
DescriptionIs this body frozen?
Method IsSleeping:Int()
DescriptionIs this body sleeping (not simulating).
Method IsStatic:Int()
DescriptionIs this body static (immovable)?
Method PutToSleep()
DescriptionPut this body to sleep so it will stop simulating.
InformationThis also sets the velocity to zero.
Method SetAngularVelocity(omega:Float)
DescriptionSet the angular velocity.
InformationParameters:
  • omega : the New angular velocity in degrees/Second.
Method SetBullet(flag:Int)
DescriptionShould this body be treated like a bullet for continuous collision detection?
Method SetLinearVelocity(v:b2Vec2)
DescriptionSet the linear velocity of the center of mass.
InformationParameters:
  • v : the New linear velocity of the center of mass.
Method SetMass(massData:b2MassData)
DescriptionSet the mass properties.
InformationNote that this changes the center of mass position.

If you are not sure how to compute mass properties, use SetMassFromShapes.

The inertia tensor is assumed to be relative to the center of mass.

Method SetMassFromShapes()
DescriptionCompute the mass properties from the attached shapes.
InformationYou typically call this after adding all the shapes. If you add or remove shapes later, you may want to call this again. Note that this changes the center of mass position.
Method SetXForm:Int(position:b2Vec2, angle:Float)
DescriptionSet the position of the body's origin and rotation (degrees).
InformationThis breaks any contacts and wakes the other bodies.
Method WakeUp()
DescriptionWake up this body so it will begin simulating.

Type b2BodyDef
DescriptionA body definition holds all the data needed to construct a rigid body.
InformationYou can safely re-use body definitions.
Methods Summary
GetAllowSleep Returns true if the body is allowed to sleep.
GetAngle Returns the world angle of the body in degrees.
GetAngularDamping Returns the angular damping.
GetFixedRotation Returns True if rotation is fixed.
GetIsBullet Returns whether this is a bullet type body.
GetLinearDamping Returns the linear damping.
GetMassData Returns mass property data.
GetPosition Returns the world position of the body.
GetUserData Returns the application specific body data, if any.
isSleeping Is this body initially sleeping?
SetAllowSleep Set this flag to False if this body should never fall asleep.
SetAngle The world angle of the body in degrees.
SetAngularDamping Angular damping is used to reduce the angular velocity.
SetFixedRotation Should this body be prevented from rotating? Useful For characters.
SetIsBullet Is this a fast moving body that should be prevented from tunneling through other moving bodies?
SetIsSleeping Enables/Disables the sleeping state of the body.
SetLinearDamping Linear damping is used to reduce the linear velocity.
SetMassData You can use this to initialize the mass properties of the body.
SetPosition The world position of the body.
SetPositionXY The world position of the body.
SetUserData Use this to store application specific body data.
Method GetAllowSleep:Int()
DescriptionReturns true if the body is allowed to sleep.
Method GetAngle:Float()
DescriptionReturns the world angle of the body in degrees.
Method GetAngularDamping:Float()
DescriptionReturns the angular damping.
Method GetFixedRotation:Int()
DescriptionReturns True if rotation is fixed.
Method GetIsBullet:Int()
DescriptionReturns whether this is a bullet type body.
Method GetLinearDamping:Float()
DescriptionReturns the linear damping.
Method GetMassData:b2MassData()
DescriptionReturns mass property data.
Method GetPosition:b2Vec2()
DescriptionReturns the world position of the body.
Method GetUserData:Object()
DescriptionReturns the application specific body data, if any.
Method isSleeping:Int()
DescriptionIs this body initially sleeping?
Method SetAllowSleep(allow:Int)
DescriptionSet this flag to False if this body should never fall asleep.
InformationNote that this increases CPU usage.
Method SetAngle(angle:Float)
DescriptionThe world angle of the body in degrees.
Method SetAngularDamping(damping:Float)
DescriptionAngular damping is used to reduce the angular velocity.
InformationThe damping parameter can be larger than 1.0 but the damping effect becomes sensitive to the time Step when the damping parameter is large.
Method SetFixedRotation(fixed:Int)
DescriptionShould this body be prevented from rotating? Useful For characters.
Method SetIsBullet(bullet:Int)
DescriptionIs this a fast moving body that should be prevented from tunneling through other moving bodies?
InformationNote that all bodies are prevented from tunneling through static bodies.

Warning: You should use this flag sparingly since it increases processing time.

Method SetIsSleeping(sleeping:Int)
DescriptionEnables/Disables the sleeping state of the body.
Method SetLinearDamping(damping:Float)
DescriptionLinear damping is used to reduce the linear velocity.
InformationThe damping parameter can be larger than 1.0 but the damping effect becomes sensitive To the time Step when the damping parameter is large.
Method SetMassData(data:b2MassData)
DescriptionYou can use this to initialize the mass properties of the body.
InformationIf you prefer, you can set the mass properties after the shapes have been added using b2Body.SetMassFromShapes.
Method SetPosition(position:b2Vec2)
DescriptionThe world position of the body.
InformationAvoid creating bodies at the origin since this can lead to many overlapping shapes.
Method SetPositionXY(x:Float, y:Float)
DescriptionThe world position of the body.
InformationAvoid creating bodies at the origin since this can lead to many overlapping shapes.
Method SetUserData(data:Object)
DescriptionUse this to store application specific body data.

Type b2BoundaryListener
DescriptionUse this type for when a body's shape passes outside of the world boundary.
InformationOverride Violation().
Methods Summary
Violation This is called for each body that leaves the world boundary.
Method Violation(body:b2Body)
DescriptionThis is called for each body that leaves the world boundary.
InformationWarning: you can't modify the world inside this callback.

Type b2BuoyancyController Extends b2Controller
DescriptionCalculates buoyancy forces for fluids in the form of a half plane.
Methods Summary
GetAngularDrag Returns the angular drag co-efficient.
GetDensity Returns the fluid density.
GetGravity Returns the gravity vector, if the world's gravity is not used.
GetLinearDrag Returns the linear drag co-efficient.
GetNormal Returns the outer surface normal.
GetOffset Returns the height of the fluid surface along the normal.
GetVelocity Returns the fluid velocity, for drag calculations.
SetAngularDrag Sets the angular drag co-efficient.
SetDensity Sets the fluid density.
SetGravity Returns the gravity vector, if the world's gravity is not used.
SetLinearDrag Sets the linear drag co-efficient.
SetNormal Sets the outer surface normal.
SetOffset Sets the height of the fluid surface along the normal.
SetUsesDensity Set to False, if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
SetUsesWorldGravity Set to True, if gravity is to be taken from the world instead of the gravity parameter.
SetVelocity Sets the fluid velocity, for drag calculations.
UsesDensity Returns False if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
UsesWorldGravity Returns True, if gravity is taken from the world instead of the gravity parameter.
Method GetAngularDrag:Float()
DescriptionReturns the angular drag co-efficient.
Method GetDensity:Float()
DescriptionReturns the fluid density.
Method GetGravity:b2Vec2()
DescriptionReturns the gravity vector, if the world's gravity is not used.
Method GetLinearDrag:Float()
DescriptionReturns the linear drag co-efficient.
Method GetNormal:b2Vec2()
DescriptionReturns the outer surface normal.
Method GetOffset:Float()
DescriptionReturns the height of the fluid surface along the normal.
Method GetVelocity:b2Vec2()
DescriptionReturns the fluid velocity, for drag calculations.
Method SetAngularDrag(drag:Float)
DescriptionSets the angular drag co-efficient.
Method SetDensity(density:Float)
DescriptionSets the fluid density.
Method SetGravity(gravity:b2Vec2)
DescriptionReturns the gravity vector, if the world's gravity is not used.
Method SetLinearDrag(drag:Float)
DescriptionSets the linear drag co-efficient.
Method SetNormal(normal:b2Vec2)
DescriptionSets the outer surface normal.
Method SetOffset(offset:Float)
DescriptionSets the height of the fluid surface along the normal.
Method SetUsesDensity(value:Int)
DescriptionSet to False, if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
Method SetUsesWorldGravity(value:Int)
DescriptionSet to True, if gravity is to be taken from the world instead of the gravity parameter.
Method SetVelocity(velocity:b2Vec2)
DescriptionSets the fluid velocity, for drag calculations.
Method UsesDensity:Int()
DescriptionReturns False if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
Method UsesWorldGravity:Int()
DescriptionReturns True, if gravity is taken from the world instead of the gravity parameter.

Type b2BuoyancyControllerDef Extends b2ControllerDef
DescriptionUsed to build buoyancy controllers.
Methods Summary
GetAngularDrag Returns the angular drag co-efficient.
GetDensity Returns the fluid density.
GetGravity Returns the gravity vector, if the world's gravity is not used.
GetLinearDrag Returns the linear drag co-efficient.
GetNormal Returns the outer surface normal.
GetOffset Returns the height of the fluid surface along the normal.
GetVelocity Returns the fluid velocity, for drag calculations.
SetAngularDrag Sets the angular drag co-efficient.
SetDensity Sets the fluid density.
SetGravity Returns the gravity vector, if the world's gravity is not used.
SetLinearDrag Sets the linear drag co-efficient.
SetNormal Sets the outer surface normal.
SetOffset Sets the height of the fluid surface along the normal.
SetUsesDensity Set to False, if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
SetUsesWorldGravity Set to True, if gravity is to be taken from the world instead of the gravity parameter.
SetVelocity Sets the fluid velocity, for drag calculations.
UsesDensity Returns False if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
UsesWorldGravity Returns True, if gravity is taken from the world instead of the gravity parameter.
Method GetAngularDrag:Float()
DescriptionReturns the angular drag co-efficient.
Method GetDensity:Float()
DescriptionReturns the fluid density.
Method GetGravity:b2Vec2()
DescriptionReturns the gravity vector, if the world's gravity is not used.
Method GetLinearDrag:Float()
DescriptionReturns the linear drag co-efficient.
Method GetNormal:b2Vec2()
DescriptionReturns the outer surface normal.
Method GetOffset:Float()
DescriptionReturns the height of the fluid surface along the normal.
Method GetVelocity:b2Vec2()
DescriptionReturns the fluid velocity, for drag calculations.
Method SetAngularDrag(drag:Float)
DescriptionSets the angular drag co-efficient.
Method SetDensity(density:Float)
DescriptionSets the fluid density.
Method SetGravity(gravity:b2Vec2)
DescriptionReturns the gravity vector, if the world's gravity is not used.
Method SetLinearDrag(drag:Float)
DescriptionSets the linear drag co-efficient.
Method SetNormal(normal:b2Vec2)
DescriptionSets the outer surface normal.
Method SetOffset(offset:Float)
DescriptionSets the height of the fluid surface along the normal.
Method SetUsesDensity(value:Int)
DescriptionSet to False, if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
Method SetUsesWorldGravity(value:Int)
DescriptionSet to True, if gravity is to be taken from the world instead of the gravity parameter.
Method SetVelocity(velocity:b2Vec2)
DescriptionSets the fluid velocity, for drag calculations.
Method UsesDensity:Int()
DescriptionReturns False if bodies are assumed to be uniformly dense, otherwise use the shapes densities.
Method UsesWorldGravity:Int()
DescriptionReturns True, if gravity is taken from the world instead of the gravity parameter.

Type b2CircleDef Extends b2ShapeDef
DescriptionUsed to build circle shapes.
Methods Summary
GetLocalPosition Returns the local position.
GetRadius Returns the circle radius.
SetLocalPosition Sets the local position.
SetRadius Sets the circle radius.
Method GetLocalPosition:b2Vec2()
DescriptionReturns the local position.
Method GetRadius:Float()
DescriptionReturns the circle radius.
Method SetLocalPosition(pos:b2Vec2)
DescriptionSets the local position.
Method SetRadius(radius:Float)
DescriptionSets the circle radius.

Type b2CircleShape Extends b2Shape
DescriptionA circle shape.
Methods Summary
GetLocalPosition Get the local position of this circle in its parent body.
GetRadius Get the radius of this circle.
Method GetLocalPosition:b2Vec2()
DescriptionGet the local position of this circle in its parent body.
Method GetRadius:Float()
DescriptionGet the radius of this circle.

Type b2Color
DescriptionColor for debug drawing.
InformationEach value has the range [0,1].

Type b2ConstantAccelController Extends b2Controller
DescriptionApplies a force every frame.
Methods Summary
GetForce Returns the force to apply.
SetForce Sets the force to apply.
Method GetForce:b2Vec2()
DescriptionReturns the force to apply.
Method SetForce(force:b2Vec2)
DescriptionSets the force to apply.

Type b2ConstantAccelControllerDef Extends b2ControllerDef
DescriptionUsed to build constant acceleration controllers.
Methods Summary
GetForce Returns the force to apply.
SetForce Sets the force to apply.
Method GetForce:b2Vec2()
DescriptionReturns the force to apply.
Method SetForce(force:b2Vec2)
DescriptionSets the force to apply.

Type b2ConstantForceController Extends b2Controller
DescriptionApplies a force every frame.
Methods Summary
GetForce Returns the force to apply.
SetForce Sets the force to apply.
Method GetForce:b2Vec2()
DescriptionReturns the force to apply.
Method SetForce(force:b2Vec2)
DescriptionSets the force to apply.

Type b2ConstantForceControllerDef Extends b2ControllerDef
DescriptionUsed to build constant force controllers.
Methods Summary
GetForce Returns the force to apply.
SetForce Sets the force to apply.
Method GetForce:b2Vec2()
DescriptionReturns the force to apply.
Method SetForce(force:b2Vec2)
DescriptionSets the force to apply.

Type b2Contact
DescriptionThis type manages contact between two shapes.
InformationA contact exists for each overlapping AABB in the broad-phase (except if filtered). Therefore a contact object may exist that has no contact points.
Methods Summary
GetManifoldCount Get the number of manifolds.
GetNext Get the next contact in the world's contact list.
GetShape1 Get the first shape in this contact.
GetShape2 Get the second shape in this contact.
IsSolid Is this contact solid?
Method GetManifoldCount:Int()
DescriptionGet the number of manifolds.
InformationThis is 0 or 1 between convex shapes. This may be greater than 1 for convex-vs-concave shapes. Each manifold holds up to two contact points with a shared contact normal.
Method GetNext:b2Contact()
DescriptionGet the next contact in the world's contact list.
Method GetShape1:b2Shape()
DescriptionGet the first shape in this contact.
Method GetShape2:b2Shape()
DescriptionGet the second shape in this contact.
Method IsSolid:Int()
ReturnsTrue if this contact should generate a response.
DescriptionIs this contact solid?

Type b2ContactFilter
DescriptionImplement this type and override ShouldCollide() to provide collision filtering.
InformationIn other words, you can implement this type if you want finer control over contact creation.
Methods Summary
ShouldCollide Return True if contact calculations should be performed between these two shapes.
Method ShouldCollide:Int(shape1:b2Shape, shape2:b2Shape)
DescriptionReturn True if contact calculations should be performed between these two shapes.
InformationWarning: for performance reasons this is only called when the AABBs begin to overlap.

Type b2ContactListener
DescriptionImplement this type to get collision results.
InformationYou can use these results for things like sounds and game logic. You can also get contact results by traversing the contact lists after the time step. However, you might miss some contacts because continuous physics leads to sub-stepping. Additionally you may receive multiple callbacks for the same contact in a single time step. You should strive to make your callbacks efficient because there may be many callbacks per time step.
Methods Summary
Add Called when a contact point is added.
Persist Called when a contact point persists.
Remove Called when a contact point is removed.
Result Called after a contact point is solved.
Method Add(point:b2ContactPoint)
DescriptionCalled when a contact point is added.
InformationThis includes the geometry and the forces.
Method Persist(point:b2ContactPoint)
DescriptionCalled when a contact point persists.
InformationThis includes the geometry and the forces.
Method Remove(point:b2ContactPoint)
DescriptionCalled when a contact point is removed.
InformationThis includes the last computed geometry and forces.
Method Result(result:b2ContactResult)
DescriptionCalled after a contact point is solved.

Type b2ContactPoint
DescriptionThis type is used to report contact points.
Methods Summary
GetFriction Returns the combined friction coefficient.
GetNormal Points from shape1 to shape2.
GetPosition Returns position in world coordinates.
GetRestitution Returns the combined restitution coefficient.
GetSeparation The separation is negative when shapes are touching.
GetShape1 Returns the first shape.
GetShape2 Returns the second shape.
GetVelocity Returns the velocity of point on body2 relative to point on body1 (pre-solver).
Method GetFriction:Float()
DescriptionReturns the combined friction coefficient.
Method GetNormal:b2Vec2()
DescriptionPoints from shape1 to shape2.
Method GetPosition:b2Vec2()
DescriptionReturns position in world coordinates.
Method GetRestitution:Float()
DescriptionReturns the combined restitution coefficient.
Method GetSeparation:Float()
DescriptionThe separation is negative when shapes are touching.
Method GetShape1:b2Shape()
DescriptionReturns the first shape.
Method GetShape2:b2Shape()
DescriptionReturns the second shape.
Method GetVelocity:b2Vec2()
DescriptionReturns the velocity of point on body2 relative to point on body1 (pre-solver).

Type b2ContactResult
DescriptionThis type is used to report contact point results.
Methods Summary
GetNormal Points from shape1 to shape2.
GetNormalImpulse Returns the normal impulse applied to body2.
GetPosition Returns position in world coordinates.
GetShape1 Returns the first shape.
GetShape2 Returns the second shape.
GetTangentImpulse Returns the tangent impulse applied to body2.
Method GetNormal:b2Vec2()
DescriptionPoints from shape1 to shape2.
Method GetNormalImpulse:Float()
DescriptionReturns the normal impulse applied to body2.
Method GetPosition:b2Vec2()
DescriptionReturns position in world coordinates.
Method GetShape1:b2Shape()
DescriptionReturns the first shape.
Method GetShape2:b2Shape()
DescriptionReturns the second shape.
Method GetTangentImpulse:Float()
DescriptionReturns the tangent impulse applied to body2.

Type b2Controller
DescriptionBase type for controllers.
InformationControllers are a convience for encapsulating common per-step functionality.
Methods Summary
AddBody Adds a body to the controller list.
Clear Removes all bodies from the controller list.
GetBodyList Get the attached body list.
GetNext Get the next controller in the world's body list.
GetUserData Get the user data that was provided in the controller definition.
GetWorld Get the parent world of this body.
RemoveBody Removes a body from the controller list.
Method AddBody(body:b2Body)
DescriptionAdds a body to the controller list.
Method Clear()
DescriptionRemoves all bodies from the controller list.
Method GetBodyList:b2ControllerEdge()
DescriptionGet the attached body list.
Method GetNext:b2Controller()
DescriptionGet the next controller in the world's body list.
Method GetUserData:Object()
DescriptionGet the user data that was provided in the controller definition.
Method GetWorld:b2World()
DescriptionGet the parent world of this body.
Method RemoveBody(body:b2Body)
DescriptionRemoves a body from the controller list.

Type b2ControllerEdge
DescriptionA controller edge is used to connect bodies and controllers together in a bipartite graph.
Methods Summary
GetBody Returns the body.
GetController Provides quick access to other end of this edge.
GetNexBody Returns the next controller edge in the controllers's joint list.
GetNextController Returns the next controller edge in the body's joint list.
GetPrevBody Returns the previous controller edge in the controllers's joint list.
GetPrevController Returns the previous controller edge in the body's joint list.
Method GetBody:b2Body()
DescriptionReturns the body.
Method GetController:b2Controller()
DescriptionProvides quick access to other end of this edge.
Method GetNexBody:b2ControllerEdge()
DescriptionReturns the next controller edge in the controllers's joint list.
Method GetNextController:b2ControllerEdge()
DescriptionReturns the next controller edge in the body's joint list.
Method GetPrevBody:b2ControllerEdge()
DescriptionReturns the previous controller edge in the controllers's joint list.
Method GetPrevController:b2ControllerEdge()
DescriptionReturns the previous controller edge in the body's joint list.

Type b2DebugDraw
DescriptionImplement and register this type with a b2World to provide debug drawing of physics entities in your game.
Methods Summary
AppendFlags Append flags to the current flags.
ClearFlags Clear flags from the current flags.
DrawCircle Draw a circle.
DrawPolygon Draw a closed polygon provided in CCW order.
DrawSegment Draw a line segment.
DrawSolidCircle Draw a solid circle.
DrawSolidPolygon Draw a solid closed polygon provided in CCW order.
DrawXForm Draw a transform. Choose your own length scale.
GetFlags Get the drawing flags.
SetFlags Set the drawing flags.
Method AppendFlags(flags:Int)
DescriptionAppend flags to the current flags.
Method ClearFlags(flags:Int)
DescriptionClear flags from the current flags.
Method DrawCircle(center:b2Vec2, radius:Float, color:b2Color) Abstract
DescriptionDraw a circle.
Method DrawPolygon(vertices:b2Vec2[], color:b2Color) Abstract
DescriptionDraw a closed polygon provided in CCW order.
Method DrawSegment(p1:b2Vec2, p2:b2Vec2, color:b2Color) Abstract
DescriptionDraw a line segment.
Method DrawSolidCircle(center:b2Vec2, radius:Float, axis:b2Vec2, color:b2Color) Abstract
DescriptionDraw a solid circle.
Method DrawSolidPolygon(vertices:b2Vec2[], color:b2Color) Abstract
DescriptionDraw a solid closed polygon provided in CCW order.
Method DrawXForm(xf:b2XForm) Abstract
DescriptionDraw a transform. Choose your own length scale.
Method GetFlags:Int()
DescriptionGet the drawing flags.
Method SetFlags(flags:Int)
DescriptionSet the drawing flags.

Type b2DestructionListener
DescriptionJoints and shapes are destroyed when their associated body is destroyed.
InformationImplement this listener so that you may nullify references to these joints and shapes.
Methods Summary
SayGoodbyeJoint Called when any joint is about to be destroyed due to the destruction of one of its attached bodies.
SayGoodbyeShape Called when any shape is about to be destroyed due to the destruction of its parent body.
Method SayGoodbyeJoint(joint:b2Joint)
DescriptionCalled when any joint is about to be destroyed due to the destruction of one of its attached bodies.
Method SayGoodbyeShape(shape:b2Shape)
DescriptionCalled when any shape is about to be destroyed due to the destruction of its parent body.

Type b2DistanceJoint Extends b2Joint
DescriptionA distance joint constrains two points on two bodies to remain at a fixed distance from each other.
InformationYou can view this as a massless, rigid rod.
Methods Summary
GetAnchor1 Get the anchor point on body1 in world coordinates.
GetAnchor2 Get the anchor point on body2 in world coordinates.
GetReactionForce Get the reaction force on body2 at the joint anchor.
GetReactionTorque Get the reaction torque on body2.
Method GetAnchor1:b2Vec2()
DescriptionGet the anchor point on body1 in world coordinates.
Method GetAnchor2:b2Vec2()
DescriptionGet the anchor point on body2 in world coordinates.
Method GetReactionForce:b2Vec2(inv_dt:Float)
DescriptionGet the reaction force on body2 at the joint anchor.
Method GetReactionTorque:Float(inv_dt:Float)
DescriptionGet the reaction torque on body2.

Type b2DistanceJointDef Extends b2JointDef
DescriptionDistance joint definition.
InformationThis requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game.

Warning: Do not use a zero or short length.

Methods Summary
GetLength Returns the equilibrium length between the anchor points.
GetLocalAnchor1 Returns the local anchor point relative to body1's origin.
GetLocalAnchor2 Returns the Local anchor point relative to body2's origin.
Initialize Initialize the bodies, anchors, and length using the world anchors.
SetDampingRatio Sets the damping ratio. 0 = no damping, 1 = critical damping.
SetFrequencyHz Sets the response speed.
SetLength Sets the equilibrium length between the anchor points.
SetLocalAnchor1 Sets the local anchor point relative to body1's origin.
SetLocalAnchor2 Sets the Local anchor point relative to body2's origin.
Method GetLength:Float()
DescriptionReturns the equilibrium length between the anchor points.
Method GetLocalAnchor1:b2Vec2()
DescriptionReturns the local anchor point relative to body1's origin.
Method GetLocalAnchor2:b2Vec2()
DescriptionReturns the Local anchor point relative to body2's origin.
Method Initialize(body1:b2Body, body2:b2Body, anchor1:b2Vec2, anchor2:b2Vec2)
DescriptionInitialize the bodies, anchors, and length using the world anchors.
Method SetDampingRatio(ratio:Float)
DescriptionSets the damping ratio. 0 = no damping, 1 = critical damping.
Method SetFrequencyHz(freq:Float)
DescriptionSets the response speed.
Method SetLength(length:Float)
DescriptionSets the equilibrium length between the anchor points.
Method SetLocalAnchor1(anchor:b2Vec2)
DescriptionSets the local anchor point relative to body1's origin.
Method SetLocalAnchor2(anchor:b2Vec2)
DescriptionSets the Local anchor point relative to body2's origin.

Type b2EdgeChainDef Extends b2ShapeDef
Methods Summary
GetVertices  
isALoop  
SetIsALoop  
SetVertices  
Method GetVertices:b2Vec2[]()
Method isALoop:Int()
Method SetIsALoop(value:Int)
Method SetVertices(vertices:b2Vec2[])

Type b2EdgeShape Extends b2Shape

Type b2FilterData
DescriptionThis holds contact filtering data.
Methods Summary
GetCategoryBits Returns the collision category bits.
GetGroupIndex Returns the collision group index.
GetMaskBits Returns the collision mask bits.
SetCategoryBits Sets the collision category bits.
SetGroupIndex Sets the collision group index.
SetMaskBits Sets the collision mask bits.
Method GetCategoryBits:Short()
DescriptionReturns the collision category bits.
Method GetGroupIndex:Short()
DescriptionReturns the collision group index.
InformationCollision groups allow a certain group of objects to never collide (negative) or always collide (positive).

Zero means no collision group. Non-zero group filtering always wins against the mask bits.

Method GetMaskBits:Short()
DescriptionReturns the collision mask bits.
InformationThis states the categories that this shape would accept for collision.
Method SetCategoryBits(categoryBits:Short)
DescriptionSets the collision category bits.
InformationNormally you would just set one bit.
Method SetGroupIndex(index:Short)
DescriptionSets the collision group index.
InformationCollision groups allow a certain group of objects to never collide (negative) or always collide (positive).

Zero means no collision group. Non-zero group filtering always wins against the mask bits.

Method SetMaskBits(maskBits:Short)
DescriptionSets the collision mask bits.
InformationThis states the categories that this shape would accept for collision.

Type b2GearJoint Extends b2Joint
DescriptionA gear joint is used to connect two joints together.
InformationEither joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together:
coordinate1 + ratio * coordinate2 = constant
The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length.

Warning: The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those joints).

Methods Summary
GetAnchor1 Get the anchor point on body1 in world coordinates.
GetAnchor2 Get the anchor point on body2 in world coordinates.
GetRatio Get the gear ratio.
GetReactionForce Get the reaction force on body2 at the joint anchor.
GetReactionTorque Get the reaction torque on body2.
Method GetAnchor1:b2Vec2()
DescriptionGet the anchor point on body1 in world coordinates.
Method GetAnchor2:b2Vec2()
DescriptionGet the anchor point on body2 in world coordinates.
Method GetRatio:Float()
DescriptionGet the gear ratio.
Method GetReactionForce:b2Vec2(inv_dt:Float)
DescriptionGet the reaction force on body2 at the joint anchor.
Method GetReactionTorque:Float(inv_dt:Float)
DescriptionGet the reaction torque on body2.

Type b2GearJointDef Extends b2JointDef
DescriptionGear joint definition.
InformationThis definition requires two existing revolute or prismatic joints (any combination will work). The provided joints must attach a dynamic body to a static body.
Methods Summary
SetJoint1 Sets the first revolute/prismatic joint attached to the gear joint.
SetJoint2 Sets the second revolute/prismatic joint attached to the gear joint.
SetRatio Sets the gear ratio.
Method SetJoint1(joint:b2Joint)
DescriptionSets the first revolute/prismatic joint attached to the gear joint.
Method SetJoint2(joint:b2Joint)
DescriptionSets the second revolute/prismatic joint attached to the gear joint.
Method SetRatio(ratio:Float)
DescriptionSets the gear ratio.

Type b2GravityController Extends b2Controller
DescriptionApplies simplified gravity between every pair of bodies.
Methods Summary
GetForce Returns the strength of the gravitiation force.
IsInvSqr Returns whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
SetForce Sets the strength of the gravitiation force.
SetIsInvSqr Sets whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
Method GetForce:Float()
DescriptionReturns the strength of the gravitiation force.
Method IsInvSqr:Int()
DescriptionReturns whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
Method SetForce(force:Float)
DescriptionSets the strength of the gravitiation force.
Method SetIsInvSqr(value:Int)
DescriptionSets whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).

Type b2GravityControllerDef Extends b2ControllerDef
DescriptionUsed to build gravity controllers.
Methods Summary
GetForce Returns the strength of the gravitiation force.
IsInvSqr Returns whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
SetForce Sets the strength of the gravitiation force.
SetIsInvSqr Sets whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
Method GetForce:Float()
DescriptionReturns the strength of the gravitiation force.
Method IsInvSqr:Int()
DescriptionReturns whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).
Method SetForce(force:Float)
DescriptionSets the strength of the gravitiation force.
Method SetIsInvSqr(value:Int)
DescriptionSets whether gravity is proportional to r^-2 (True), otherwise r^-1 (False).

Type b2Joint
DescriptionThe base joint type.
InformationJoints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors.
Methods Summary
GetBody1 Get the first body attached to this joint.
GetBody2 Get the second body attached to this joint.
GetNext Get the next joint the world joint list.
GetUserData Get the user data pointer that was provided in the joint definition.
Method GetBody1:b2Body()
DescriptionGet the first body attached to this joint.
Method GetBody2:b2Body()
DescriptionGet the second body attached to this joint.
Method GetNext:b2Joint()
DescriptionGet the next joint the world joint list.
Method GetUserData:Object()
DescriptionGet the user data pointer that was provided in the joint definition.

Type b2JointDef
DescriptionJoint definitions are used to construct joints.
Methods Summary
GetBody1 Returns the first attached body.
GetBody2 Returns the second attached body.
GetCollideConnected Returns True if the attached bodies should collide.
SetBody1 The First attached body.
SetBody2 The Second attached body.
SetCollideConnected Set this flag to True if the attached bodies should collide.
Method GetBody1:b2Body()
DescriptionReturns the first attached body.
Method GetBody2:b2Body()
DescriptionReturns the second attached body.
Method GetCollideConnected:Int()
DescriptionReturns True if the attached bodies should collide.
Method SetBody1(body:b2Body)
DescriptionThe First attached body.
Method SetBody2(body:b2Body)
DescriptionThe Second attached body.
Method SetCollideConnected(collideConnected:Int)
DescriptionSet this flag to True if the attached bodies should collide.

Type b2JointEdge
DescriptionA joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge.
InformationA joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body.
Methods Summary
GetJoint Returns the joint.
GetNext Returns the next joint edge in the body's joint list.
GetOther Provides quick access to the other body attached.
GetPrev Returns the previous joint edge in the body's joint list.
Method GetJoint:b2Joint()
DescriptionReturns the joint.
Method GetNext:b2JointEdge()
DescriptionReturns the next joint edge in the body's joint list.
Method GetOther:b2Body()
DescriptionProvides quick access to the other body attached.
Method GetPrev:b2JointEdge()
DescriptionReturns the previous joint edge in the body's joint list.

Type b2LineJoint Extends b2Joint
DescriptionA line joint.
InformationThis joint provides one degree of freedom: translation along an axis fixed in body1. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction.
Methods Summary
EnableLimit Enable/disable the joint limit.
EnableMotor Enable/disable the joint motor.
GetAnchor1  
GetAnchor2  
GetJointSpeed Get the current joint translation speed, usually in meters per second.
GetJointTranslation Get the current joint translation, usually in meters.
GetLowerLimit Get the lower joint limit, usually in meters.
GetMotorForce Get the current motor force, usually in N.
GetMotorSpeed Get the motor speed, usually in meters per second.
GetReactionForce  
GetReactionTorque  
GetUpperLimit Get the upper joint limit, usually in meters.
IsLimitEnabled Is the joint limit enabled?
IsMotorEnabled Is the joint motor enabled?
SetLimits Set the joint limits, usually in meters.
SetMaxMotorForce Set the maximum motor force, usually in N.
SetMotorSpeed Set the motor speed, usually in meters per second.
Method EnableLimit(flag:Int)
DescriptionEnable/disable the joint limit.
Method EnableMotor(flag:Int)
DescriptionEnable/disable the joint motor.
Method GetAnchor1:b2Vec2()
Method GetAnchor2:b2Vec2()
Method GetJointSpeed:Float()
DescriptionGet the current joint translation speed, usually in meters per second.
Method GetJointTranslation:Float()
DescriptionGet the current joint translation, usually in meters.
Method GetLowerLimit:Float()
DescriptionGet the lower joint limit, usually in meters.
Method GetMotorForce:Float()
DescriptionGet the current motor force, usually in N.
Method GetMotorSpeed:Float()
DescriptionGet the motor speed, usually in meters per second.
Method GetReactionForce:b2Vec2(inv_dt:Float)
Method GetReactionTorque:Float(inv_dt:Float)
Method GetUpperLimit:Float()
DescriptionGet the upper joint limit, usually in meters.
Method IsLimitEnabled:Int()
DescriptionIs the joint limit enabled?
Method IsMotorEnabled:Int()
DescriptionIs the joint motor enabled?
Method SetLimits(_lower:Float, _upper:Float)
DescriptionSet the joint limits, usually in meters.
Method SetMaxMotorForce(force:Float)
DescriptionSet the maximum motor force, usually in N.
Method SetMotorSpeed(speed:Float)
DescriptionSet the motor speed, usually in meters per second.

Type b2LineJointDef Extends b2JointDef
DescriptionLine joint definition.
InformationThis requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.
Methods Summary
EnableLimit Enables/disables the joint limit.
EnableMotor Enables/disables the joint motor.
GetLimit Returns the joint limit.
GetLocalAnchor1 Returns the local anchor point relative to body1's origin.
GetLocalAnchor2 Returns the Local anchor point relative to body2's origin.
GetLocalAxis1 Returns the local translation axis in body1.
GetLowerTranslation Gets the lower translation limit, usually in meters.
GetMaxMotorForce Returns the maximum motor torque, usually in N-m.
GetMotorSpeed Returns the desired motor speed, in degrees per second.
GetUpperTranslation Gets the upper translation limit, usually in meters.
Initialize Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
IsMotorEnabled Is the motor enabled?
SetLocalAnchor1 Sets the local anchor point relative to body1's origin.
SetLocalAnchor2 Sets the Local anchor point relative to body2's origin.
SetLocalAxis1 Sets the local translation axis in body1.
SetLowerTranslation Sets the lower translation limit, usually in meters.
SetMaxMotorForce Sets the maximum motor torque, usually in N-m.
SetMotorSpeed Sets the desired motor speed, in degrees per second.
SetUpperTranslation Sets the upper translation limit, usually in meters.
Method EnableLimit(limit:Int)
DescriptionEnables/disables the joint limit.
Method EnableMotor(enable:Int)
DescriptionEnables/disables the joint motor.
Method GetLimit:Int()
DescriptionReturns the joint limit.
Method GetLocalAnchor1:b2Vec2()
DescriptionReturns the local anchor point relative to body1's origin.
Method GetLocalAnchor2:b2Vec2()
DescriptionReturns the Local anchor point relative to body2's origin.
Method GetLocalAxis1:b2Vec2()
DescriptionReturns the local translation axis in body1.
Method GetLowerTranslation:Float()
DescriptionGets the lower translation limit, usually in meters.
Method GetMaxMotorForce:Float()
DescriptionReturns the maximum motor torque, usually in N-m.
Method GetMotorSpeed:Float()
DescriptionReturns the desired motor speed, in degrees per second.
Method GetUpperTranslation:Float()
DescriptionGets the upper translation limit, usually in meters.
Method Initialize(body1:b2Body, body2:b2Body, anchor:b2Vec2, axis:b2Vec2)
DescriptionInitialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
Method IsMotorEnabled:Int()
DescriptionIs the motor enabled?
Method SetLocalAnchor1(anchor:b2Vec2)
DescriptionSets the local anchor point relative to body1's origin.
Method SetLocalAnchor2(anchor:b2Vec2)
DescriptionSets the Local anchor point relative to body2's origin.
Method SetLocalAxis1(axis:b2Vec2)
DescriptionSets the local translation axis in body1.
Method SetLowerTranslation(translation:Float)
DescriptionSets the lower translation limit, usually in meters.
Method SetMaxMotorForce(maxForce:Float)
DescriptionSets the maximum motor torque, usually in N-m.
Method SetMotorSpeed(speed:Float)
DescriptionSets the desired motor speed, in degrees per second.
Method SetUpperTranslation(translation:Float)
DescriptionSets the upper translation limit, usually in meters.

Type b2MassData
DescriptionHolds the mass data computed for a shape.
Methods Summary
SetCenter Sets the position of the shape's centroid relative to the shape's origin.
SetMass Sets the mass of the shape, usually in kilograms.
SetRotationalInertia Sets the rotational inertia of the shape.
Method SetCenter(center:b2Vec2)
DescriptionSets the position of the shape's centroid relative to the shape's origin.
Method SetMass(mass:Float)
DescriptionSets the mass of the shape, usually in kilograms.
Method SetRotationalInertia(i:Float)
DescriptionSets the rotational inertia of the shape.

Type b2Mat22
DescriptionA 2-by-2 matrix.
InformationStored in column-major order.
Methods Summary
Create Constructs the matrix using scalars.
CreateAngle Constructs the matrix using an angle.
CreateVec Constructs the matrix using columns.
GetAngle Returns the angle.
GetInverse Computes the inverse of this matrix, such that inv(A) * A = identity.
SetAngle Initialize this matrix using an angle.
SetIdentity Set this to the identity matrix.
SetZero Set this matrix to all zeros.
Method Create:b2Mat22(a11:Float = 0, a12:Float = 0, a21:Float = 0, a22:Float = 0)
DescriptionConstructs the matrix using scalars.
Method CreateAngle:b2Mat22(angle:Float)
DescriptionConstructs the matrix using an angle.
InformationThis matrix becomes an orthonormal rotation matrix.
Method CreateVec:b2Mat22(c1:b2Vec2, c2:b2Vec2)
DescriptionConstructs the matrix using columns.
Method GetAngle:Float()
DescriptionReturns the angle.
Method GetInverse:b2Mat22()
DescriptionComputes the inverse of this matrix, such that inv(A) * A = identity.
Method SetAngle(angle:Float)
DescriptionInitialize this matrix using an angle.
InformationThis matrix becomes an orthonormal rotation matrix.
Method SetIdentity()
DescriptionSet this to the identity matrix.
Method SetZero()
DescriptionSet this matrix to all zeros.

Type b2MouseJoint Extends b2Joint
DescriptionA mouse joint is used to make a point on a body track a specified world point.
InformationThis a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces.
Methods Summary
GetAnchor1 Get the anchor point on body1 in world coordinates.
GetAnchor2 Get the anchor point on body2 in world coordinates.
GetLocalAnchor Returns the local anchor.
GetReactionForce Get the reaction force on body2 at the joint anchor.
GetReactionTorque Get the reaction torque on body2.
GetTarget Returns the target point.
SetTarget Use this to update the target point.
Method GetAnchor1:b2Vec2()
DescriptionGet the anchor point on body1 in world coordinates.
Method GetAnchor2:b2Vec2()
DescriptionGet the anchor point on body2 in world coordinates.
Method GetLocalAnchor:b2Vec2()
DescriptionReturns the local anchor.
Method GetReactionForce:b2Vec2(inv_dt:Float)
DescriptionGet the reaction force on body2 at the joint anchor.
Method GetReactionTorque:Float(inv_dt:Float)
DescriptionGet the reaction torque on body2.
Method GetTarget:b2Vec2()
DescriptionReturns the target point.
Method SetTarget(target:b2Vec2)
DescriptionUse this to update the target point.

Type b2MouseJointDef Extends b2JointDef
DescriptionMouse joint definition.
InformationThis requires a world target point, tuning parameters, and the time step.
Methods Summary
GetDampingRatio Returns the damping ratio.
GetFrequencyHz Returns the response speed.
GetMaxForce Returns the maximum constraint force that can be exerted to move the candidate body.
GetTarget Returns the initial world target point.
SetDampingRatio The damping ratio.
SetFrequencyHz The response speed.
SetMaxForce The maximum constraint force that can be exerted to move the candidate body.
SetTarget The initial world target point.
Method GetDampingRatio:Float()
DescriptionReturns the damping ratio.
Method GetFrequencyHz:Float()
DescriptionReturns the response speed.
Method GetMaxForce:Float()
DescriptionReturns the maximum constraint force that can be exerted to move the candidate body.
Method GetTarget:b2Vec2()
DescriptionReturns the initial world target point.
Method SetDampingRatio(ratio:Float)
DescriptionThe damping ratio.
Information0 = no damping, 1 = critical damping.
Method SetFrequencyHz(frequency:Float)
DescriptionThe response speed.
Method SetMaxForce(maxForce:Float)
DescriptionThe maximum constraint force that can be exerted to move the candidate body.
InformationUsually you will express as some multiple of the weight (multiplier * mass * gravity).
Method SetTarget(target:b2Vec2)
DescriptionThe initial world target point.
InformationThis is assumed to coincide with the body anchor initially.

Type b2OBB
DescriptionAn oriented bounding box.
Methods Summary
GetCenter Returns the local centroid.
GetExtents Returns the half-widths.
GetRotationMatrix Returns the rotation matrix.
Method GetCenter:b2Vec2()
DescriptionReturns the local centroid.
Method GetExtents:b2Vec2()
DescriptionReturns the half-widths.
Method GetRotationMatrix:b2Mat22()
DescriptionReturns the rotation matrix.

Type b2PolygonDef Extends b2ShapeDef
DescriptionConvex polygon.
InformationVertices must be in CCW order.
Methods Summary
GetVertices Gets the polygon vertices in local coordinates.
SetAsBox Build vertices to represent an axis-aligned box.
SetAsOrientedBox Build vertices to represent an oriented box.
SetVertices Sets the polygon vertices in local coordinates.
Method GetVertices:b2Vec2[]()
DescriptionGets the polygon vertices in local coordinates.
Method SetAsBox(hx:Float, hy:Float)
DescriptionBuild vertices to represent an axis-aligned box.
InformationParameters:
  • hx : the half-width.
  • hy : the half-height.
Method SetAsOrientedBox(hx:Float, hy:Float, center:b2Vec2, angle:Float)
DescriptionBuild vertices to represent an oriented box.
InformationParameters:
  • hx : the half-width.
  • hy : the half-height.
  • center : the center of the box in local coordinates.
  • angle : the rotation of the box in local coordinates.
Method SetVertices(vertices:b2Vec2[])
DescriptionSets the polygon vertices in local coordinates.

Type b2PolygonShape Extends b2Shape
DescriptionA convex polygon.
Methods Summary
Centroid Get the centroid and apply the supplied transform.
GetCentroid Get local centroid relative to the parent body.
GetCoreVertices Get the core vertices in local coordinates.
GetFirstVertex Get the first vertex and apply the supplied transform.
GetNormals Get the edge normal vectors.
GetOBB Get the oriented bounding box relative to the parent body.
GetVertexCount Get the vertex count.
GetVertices Get the vertices in local coordinates.
Support Get the support point in the given world direction.
Method Centroid:b2Vec2(xf:b2XForm)
DescriptionGet the centroid and apply the supplied transform.
Method GetCentroid:b2Vec2()
DescriptionGet local centroid relative to the parent body.
Method GetCoreVertices:b2Vec2[]()
DescriptionGet the core vertices in local coordinates.
Method GetFirstVertex:b2Vec2(xf:b2XForm)
DescriptionGet the first vertex and apply the supplied transform.
Method GetNormals:b2Vec2[]()
DescriptionGet the edge normal vectors.
InformationThere is one for each vertex.
Method GetOBB:b2OBB()
DescriptionGet the oriented bounding box relative to the parent body.
Method GetVertexCount:Int()
DescriptionGet the vertex count.
Method GetVertices:b2Vec2[]()
DescriptionGet the vertices in local coordinates.
Method Support:b2Vec2(xf:b2XForm, d:b2Vec2)
DescriptionGet the support point in the given world direction.

Type b2PrismaticJoint Extends b2Joint
Methods Summary
EnableLimit Enable/disable the joint limit.
EnableMotor Enable/disable the joint motor.
GetAnchor1 Get the anchor point on body1 in world coordinates.
GetAnchor2 Get the anchor point on body2 in world coordinates.
GetJointSpeed Get the current joint translation speed, usually in meters per second.
GetJointTranslation Get the current joint translation, usually in meters.
GetLowerLimit Get the lower joint limit, usually in meters.
GetMotorForce Get the current motor force, usually in N.
GetMotorSpeed Get the motor speed, usually in meters per second.
GetReactionForce Get the reaction force on body2 at the joint anchor.
GetReactionTorque Get the reaction torque on body2.
GetUpperLimit Get the upper joint limit, usually in meters.
IsLimitEnabled Is the joint limit enabled?
IsMotorEnabled Is the joint motor enabled?
SetLimits Set the joint limits, usually in meters.
SetMaxMotorForce Set the maximum motor force, usually in N.
SetMotorSpeed Set the motor speed, usually in meters per second.
Method EnableLimit(flag:Int)
DescriptionEnable/disable the joint limit.
Method EnableMotor(flag:Int)
DescriptionEnable/disable the joint motor.
Method GetAnchor1:b2Vec2()
DescriptionGet the anchor point on body1 in world coordinates.
Method GetAnchor2:b2Vec2()
DescriptionGet the anchor point on body2 in world coordinates.
Method GetJointSpeed:Float()
DescriptionGet the current joint translation speed, usually in meters per second.
Method GetJointTranslation:Float()
DescriptionGet the current joint translation, usually in meters.
Method GetLowerLimit:Float()
DescriptionGet the lower joint limit, usually in meters.
Method GetMotorForce:Float()
DescriptionGet the current motor force, usually in N.
Method GetMotorSpeed:Float()
DescriptionGet the motor speed, usually in meters per second.
Method GetReactionForce:b2Vec2(inv_dt:Float)
DescriptionGet the reaction force on body2 at the joint anchor.
Method GetReactionTorque:Float(inv_dt:Float)
DescriptionGet the reaction torque on body2.
Method GetUpperLimit:Float()
DescriptionGet the upper joint limit, usually in meters.
Method IsLimitEnabled:Int()
DescriptionIs the joint limit enabled?
Method IsMotorEnabled:Int()
DescriptionIs the joint motor enabled?
Method SetLimits(lowerLimit:Float, upperLimit:Float)
DescriptionSet the joint limits, usually in meters.
Method SetMaxMotorForce(force:Float)
DescriptionSet the maximum motor force, usually in N.
Method SetMotorSpeed(speed:Float)
DescriptionSet the motor speed, usually in meters per second.

Type b2PrismaticJointDef Extends b2JointDef
DescriptionPrismatic joint definition.
InformationThis requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.
Methods Summary
EnableLimit Enable/disable the joint limit.
EnableMotor Enable/disable the joint motor.
GetLocalAnchor1 Returns the local anchor point.
GetLocalAnchor2 Returns the local anchor point.
GetLocalAxis1 Returns the local translation axis in body1.
GetLowerTranslation Returns the lower translation limit.
GetMaxMotorForce Returns the maximum motor torque.
GetMotorSpeed The motorspeed, in degrees per second.
GetReferenceAngle Returns the constrained angle between the bodies.
GetUpperTranslation Returns the upper translation limit.
Initialize Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
IsLimitEnabled Returns True if the joint limit is enabled.
IsMotorEnabled Returns true if the joint motor is enabled.
SetLocalAnchor1 The local anchor point relative to body1's origin.
SetLocalAnchor2 The local anchor point relative to body2's origin.
SetLocalAxis1 The local translation axis in body1.
SetLowerTranslation The lower translation limit, usually in meters.
SetMaxMotorForce The maximum motor torque, usually in N-m.
SetMotorSpeed The desired motor speed in degrees per second.
SetReferenceAngle The constrained angle between the bodies: body2_angle - body1_angle.
SetUpperTranslation The upper translation limit, usually in meters.
Method EnableLimit(value:Int)
DescriptionEnable/disable the joint limit.
Method EnableMotor(value:Int)
DescriptionEnable/disable the joint motor.
Method GetLocalAnchor1:b2Vec2()
DescriptionReturns the local anchor point.
Method GetLocalAnchor2:b2Vec2()
DescriptionReturns the local anchor point.
Method GetLocalAxis1:b2Vec2()
DescriptionReturns the local translation axis in body1.
Method GetLowerTranslation:Float()
DescriptionReturns the lower translation limit.
Method GetMaxMotorForce:Float()
DescriptionReturns the maximum motor torque.
Method GetMotorSpeed:Float()
DescriptionThe motorspeed, in degrees per second.
Method GetReferenceAngle:Float()
DescriptionReturns the constrained angle between the bodies.
Method GetUpperTranslation:Float()
DescriptionReturns the upper translation limit.
Method Initialize(body1:b2Body, body2:b2Body, anchor:b2Vec2, axis:b2Vec2)
DescriptionInitialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
Method IsLimitEnabled:Int()
DescriptionReturns True if the joint limit is enabled.
Method IsMotorEnabled:Int()
DescriptionReturns true if the joint motor is enabled.
Method SetLocalAnchor1(anchor:b2Vec2)
DescriptionThe local anchor point relative to body1's origin.
Method SetLocalAnchor2(anchor:b2Vec2)
DescriptionThe local anchor point relative to body2's origin.
Method SetLocalAxis1(axis:b2Vec2)
DescriptionThe local translation axis in body1.
Method SetLowerTranslation(translation:Float)
DescriptionThe lower translation limit, usually in meters.
Method SetMaxMotorForce(force:Float)
DescriptionThe maximum motor torque, usually in N-m.
Method SetMotorSpeed(speed:Float)
DescriptionThe desired motor speed in degrees per second.
Method SetReferenceAngle(angle:Float)
DescriptionThe constrained angle between the bodies: body2_angle - body1_angle.
Method SetUpperTranslation(translation:Float)
DescriptionThe upper translation limit, usually in meters.

Type b2PulleyJoint Extends b2Joint
DescriptionThe pulley joint is connected to two bodies and two fixed ground points.
InformationThe pulley supports a ratio such that:
length1 + ratio * length2 <= constant
Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top.
Methods Summary
GetAnchor1 Get the anchor point on body1 in world coordinates.
GetAnchor2 Get the anchor point on body2 in world coordinates.
GetGroundAnchor1 Get the first ground anchor.
GetGroundAnchor2 Get the second ground anchor.
GetLength1 Get the current length of the segment attached to body1.
GetLength2 Get the current length of the segment attached to body2.
GetRatio Get the pulley ratio.
GetReactionForce Get the reaction force on body2 at the joint anchor.
GetReactionTorque Get the reaction torque on body2.
Method GetAnchor1:b2Vec2()
DescriptionGet the anchor point on body1 in world coordinates.
Method GetAnchor2:b2Vec2()
DescriptionGet the anchor point on body2 in world coordinates.
Method GetGroundAnchor1:b2Vec2()
DescriptionGet the first ground anchor.
Method GetGroundAnchor2:b2Vec2()
DescriptionGet the second ground anchor.
Method GetLength1:Float()
DescriptionGet the current length of the segment attached to body1.
Method GetLength2:Float()
DescriptionGet the current length of the segment attached to body2.
Method GetRatio:Float()
DescriptionGet the pulley ratio.
Method GetReactionForce:b2Vec2(inv_dt:Float)
DescriptionGet the reaction force on body2 at the joint anchor.
Method GetReactionTorque:Float(inv_dt:Float)
DescriptionGet the reaction torque on body2.

Type b2PulleyJointDef Extends b2JointDef
DescriptionPulley joint definition.
InformationThis requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio.
Methods Summary
GetGroundAnchor1 Returns the first ground anchor, in world coordinates.
GetGroundAnchor2 Returns the second ground anchor, in world coordinates.
GetLength1 Returns the reference length for the segment attached to body1.
GetLength2 Returns the reference length for the segment attached to body2.
GetLocalAnchor1 Returns the local anchor point.
GetLocalAnchor2 Returns the local anchor point.
GetMaxLength1 Returns the maximum length of the segment attached to body1.
GetMaxLength2 Returns the maximum length of the segment attached to body2.
GetRatio Returns the pulley ratio.
Initialize Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
SetGroundAnchor1 The first ground anchor in world coordinates. This point never moves.
SetGroundAnchor2 The second ground anchor in world coordinates. This point never moves.
SetLength1 The a reference length for the segment attached to body1.
SetLength2 The a reference length for the segment attached to body2.
SetLocalAnchor1 The local anchor point relative to body1's origin.
SetLocalAnchor2 The local anchor point relative to body2's origin.
SetMaxLength1 The maximum length of the segment attached to body1.
SetMaxLength2 The maximum length of the segment attached to body2.
SetRatio The pulley ratio, used to simulate a block-and-tackle.
Method GetGroundAnchor1:b2Vec2()
DescriptionReturns the first ground anchor, in world coordinates.
Method GetGroundAnchor2:b2Vec2()
DescriptionReturns the second ground anchor, in world coordinates.
Method GetLength1:Float()
DescriptionReturns the reference length for the segment attached to body1.
Method GetLength2:Float()
DescriptionReturns the reference length for the segment attached to body2.
Method GetLocalAnchor1:b2Vec2()
DescriptionReturns the local anchor point.
Method GetLocalAnchor2:b2Vec2()
DescriptionReturns the local anchor point.
Method GetMaxLength1:Float()
DescriptionReturns the maximum length of the segment attached to body1.
Method GetMaxLength2:Float()
DescriptionReturns the maximum length of the segment attached to body2.
Method GetRatio:Float()
DescriptionReturns the pulley ratio.
Method Initialize(body1:b2Body, body2:b2Body, groundAnchor1:b2Vec2, groundAnchor2:b2Vec2, anchor1:b2Vec2, anchor2:b2Vec2, ratio:Float)
DescriptionInitialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
Method SetGroundAnchor1(anchor:b2Vec2)
DescriptionThe first ground anchor in world coordinates. This point never moves.
Method SetGroundAnchor2(anchor:b2Vec2)
DescriptionThe second ground anchor in world coordinates. This point never moves.
Method SetLength1(length:Float)
DescriptionThe a reference length for the segment attached to body1.
Method SetLength2(length:Float)
DescriptionThe a reference length for the segment attached to body2.
Method SetLocalAnchor1(anchor:b2Vec2)
DescriptionThe local anchor point relative to body1's origin.
Method SetLocalAnchor2(anchor:b2Vec2)
DescriptionThe local anchor point relative to body2's origin.
Method SetMaxLength1(maxLength:Float)
DescriptionThe maximum length of the segment attached to body1.
Method SetMaxLength2(maxLength:Float)
DescriptionThe maximum length of the segment attached to body2.
Method SetRatio(ratio:Float)
DescriptionThe pulley ratio, used to simulate a block-and-tackle.

Type b2RevoluteJoint Extends b2Joint
DescriptionA revolute joint constrains to bodies to share a common point while they are free to rotate about the point.
InformationThe relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated.
Methods Summary
EnableLimit Enable/disable the joint limit.
EnableMotor Enable/disable the joint motor.
GetAnchor1 Get the anchor point on body1 in world coordinates.
GetAnchor2 Get the anchor point on body2 in world coordinates.
GetJointAngle Get the current joint angle in degrees.
GetJointSpeed Get the current joint angle speed in degrees per second.
GetLowerLimit Get the lower joint limit in degrees.
GetMotorSpeed Get the motor speed in radians per second.
GetMotorTorque Get the current motor torque, usually in N-m.
GetReactionForce Get the reaction force on body2 at the joint anchor.
GetReactionTorque Get the reaction torque on body2.
GetUpperLimit Get the upper joint limit in degrees.
IsLimitEnabled Is the joint limit enabled?
IsMotorEnabled Is the joint motor enabled?
SetLimits Set the joint limits in degrees.
SetMaxMotorTorque Set the maximum motor torque, usually in N-m.
SetMotorSpeed Set the motor speed in radians per second.
Method EnableLimit(flag:Int)
DescriptionEnable/disable the joint limit.
Method EnableMotor(flag:Int)
DescriptionEnable/disable the joint motor.
Method GetAnchor1:b2Vec2()
DescriptionGet the anchor point on body1 in world coordinates.
Method GetAnchor2:b2Vec2()
DescriptionGet the anchor point on body2 in world coordinates.
Method GetJointAngle:Float()
DescriptionGet the current joint angle in degrees.
Method GetJointSpeed:Float()
DescriptionGet the current joint angle speed in degrees per second.
Method GetLowerLimit:Float()
DescriptionGet the lower joint limit in degrees.
Method GetMotorSpeed:Float()
DescriptionGet the motor speed in radians per second.
Method GetMotorTorque:Float()
DescriptionGet the current motor torque, usually in N-m.
Method GetReactionForce:b2Vec2(inv_dt:Float)
DescriptionGet the reaction force on body2 at the joint anchor.
Method GetReactionTorque:Float(inv_dt:Float)
DescriptionGet the reaction torque on body2.
Method GetUpperLimit:Float()
DescriptionGet the upper joint limit in degrees.
Method IsLimitEnabled:Float()
DescriptionIs the joint limit enabled?
Method IsMotorEnabled:Int()
DescriptionIs the joint motor enabled?
Method SetLimits(lowerLimit:Float, upperLimit:Float)
DescriptionSet the joint limits in degrees.
Method SetMaxMotorTorque(torque:Float)
DescriptionSet the maximum motor torque, usually in N-m.
Method SetMotorSpeed(speed:Float)
DescriptionSet the motor speed in radians per second.

Type b2RevoluteJointDef Extends b2JointDef
DescriptionRevolute joint definition.
InformationThis requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken.
Methods Summary
EnableLimit Enables joint limits.
EnableMotor Enables the joint motor.
GetLocalAnchor1 The local anchor point relative to body1's origin.
GetLocalAnchor2 The local anchor point relative to body2's origin.
GetLowerAngle The lower angle for the joint limit (degrees).
GetMaxMotorTorque The maximum motor torque used to achieve the desired motor speed, usually in N-m.
GetMotorSpeed The desired motor speed, usually in degrees per second.
GetReferenceAngle The body2 angle minus body1 angle in the reference state (degrees).
GetUpperAngle The upper angle for the joint limit (degrees).
Initialize Initialize the bodies, anchors, and reference angle using the world anchor.
IsLimitEnabled A flag to enable joint limits.
IsMotorEnabled A flag to enable the joint motor.
SetLocalAnchor1 Sets the local anchor point relative to body1's origin.
SetLocalAnchor2 Sets the local anchor point relative to body2's origin.
SetLowerAngle Sets the lower angle for the joint limit (degrees).
SetMaxMotorTorque Sets the maximum motor torque used to achieve the desired motor speed, usually in N-m.
SetMotorSpeed Sets the desired motor speed, usually in degrees per second.
SetReferenceAngle Sets the body2 angle minus body1 angle in the reference state (degrees).
SetUpperAngle Sets the upper angle for the joint limit (degrees).
Method EnableLimit(limit:Int)
DescriptionEnables joint limits.
Method EnableMotor(value:Int)
DescriptionEnables the joint motor.
Method GetLocalAnchor1:b2Vec2()
DescriptionThe local anchor point relative to body1's origin.
Method GetLocalAnchor2:b2Vec2()
DescriptionThe local anchor point relative to body2's origin.
Method GetLowerAngle:Float()
DescriptionThe lower angle for the joint limit (degrees).
Method GetMaxMotorTorque:Float()
DescriptionThe maximum motor torque used to achieve the desired motor speed, usually in N-m.
Method GetMotorSpeed:Float()
DescriptionThe desired motor speed, usually in degrees per second.
Method GetReferenceAngle:Float()
DescriptionThe body2 angle minus body1 angle in the reference state (degrees).
Method GetUpperAngle:Float()
DescriptionThe upper angle for the joint limit (degrees).
Method Initialize(body1:b2Body, body2:b2Body, anchor:b2Vec2)
DescriptionInitialize the bodies, anchors, and reference angle using the world anchor.
Method IsLimitEnabled:Int()
DescriptionA flag to enable joint limits.
Method IsMotorEnabled:Int()
DescriptionA flag to enable the joint motor.
Method SetLocalAnchor1(anchor:b2Vec2)
DescriptionSets the local anchor point relative to body1's origin.
Method SetLocalAnchor2(anchor:b2Vec2)
DescriptionSets the local anchor point relative to body2's origin.
Method SetLowerAngle(angle:Float)
DescriptionSets the lower angle for the joint limit (degrees).
Method SetMaxMotorTorque(torque:Float)
DescriptionSets the maximum motor torque used to achieve the desired motor speed, usually in N-m.
Method SetMotorSpeed(speed:Float)
DescriptionSets the desired motor speed, usually in degrees per second.
Method SetReferenceAngle(angle:Float)
DescriptionSets the body2 angle minus body1 angle in the reference state (degrees).
Method SetUpperAngle(angle:Float)
DescriptionSets the upper angle for the joint limit (degrees).

Type b2Segment
DescriptionA line segment.
Methods Summary
Create Creates a new b2Segment object.
CreateXY Creates a new b2Segment object.
GetEndPoint Returns the end point of this segment.
GetStartPoint Returns the start point of this segment.
SetEndPoint Sets the end point of this segment.
SetStartPoint Sets the start point of this segment.
Method Create:b2Segment(p1:b2Vec2 = Null, p2:b2Vec2 = Null)
DescriptionCreates a new b2Segment object.
Method CreateXY:b2Segment(x1:Float, y1:Float, x2:Float, y2:Float)
DescriptionCreates a new b2Segment object.
Method GetEndPoint:b2Vec2()
DescriptionReturns the end point of this segment.
Method GetStartPoint:b2Vec2()
DescriptionReturns the start point of this segment.
Method SetEndPoint(point:b2Vec2)
DescriptionSets the end point of this segment.
Method SetStartPoint(point:b2Vec2)
DescriptionSets the start point of this segment.

Type b2Shape
DescriptionA shape is used for collision detection.
InformationShapes are created in b2World. You can use shape for collision detection before they are attached to the world.

Warning: You cannot reuse shapes.

Methods Summary
ComputeAABB Given a transform, compute the associated axis aligned bounding box for this shape.
ComputeMass Compute the mass properties of this shape using its dimensions and density.
ComputeSweptAABB Given two transforms, compute the associated swept axis aligned bounding box for this shape.
GetBody Get the parent body of this shape.
GetFilterData Get the contact filtering data.
GetFriction Get the coefficient of friction.
GetNext Get the next shape in the parent body's shape list.
GetRestitution Get the coefficient of restitution.
GetSweepRadius Get the maximum radius about the parent body's center of mass.
GetUserData Get the user data that was assigned in the shape definition.
IsSensor Is this shape a sensor (non-solid)?
SetFilterData Set the contact filtering data.
SetFriction Set the coefficient of friction.
SetRestitution Set the coefficient of restitution.
SetUserData Sets the user data.
TestPoint Test a point for containment in this shape.
Method ComputeAABB(aabb:b2AABB, xf:b2XForm)
DescriptionGiven a transform, compute the associated axis aligned bounding box for this shape.
Method ComputeMass(data:b2MassData)
Returnsthe mass data for this shape.
DescriptionCompute the mass properties of this shape using its dimensions and density.
InformationThe inertia tensor is computed about the local origin, not the centroid.
Method ComputeSweptAABB(aabb:b2AABB, xf1:b2XForm, xf2:b2XForm)
DescriptionGiven two transforms, compute the associated swept axis aligned bounding box for this shape.
Method GetBody:b2Body()
DescriptionGet the parent body of this shape.
Method GetFilterData:b2FilterData()
DescriptionGet the contact filtering data.
Method GetFriction:Float()
DescriptionGet the coefficient of friction.
Method GetNext:b2Shape()
DescriptionGet the next shape in the parent body's shape list.
Method GetRestitution:Float()
DescriptionGet the coefficient of restitution.
Method GetSweepRadius:Float()
DescriptionGet the maximum radius about the parent body's center of mass.
Method GetUserData:Object()
DescriptionGet the user data that was assigned in the shape definition.
Method IsSensor:Int()
DescriptionIs this shape a sensor (non-solid)?
Method SetFilterData(data:b2FilterData)
DescriptionSet the contact filtering data.
InformationYou must call b2World::Refilter to correct existing contacts/non-contacts.
Method SetFriction(friction:Float)
DescriptionSet the coefficient of friction.
Method SetRestitution(restitution:Float)
DescriptionSet the coefficient of restitution.
Method SetUserData(data:Object)
DescriptionSets the user data.
Method TestPoint:Int(xf:b2XForm, p:b2Vec2)
DescriptionTest a point for containment in this shape.
InformationThis only works for convex shapes.

Type b2ShapeDef
DescriptionA shape definition is used to construct a shape.
InformationYou can reuse shape definitions safely.
Methods Summary
GetDensity Gets the shape's density, usually in kg/m^2.
GetFilter Returns the contact filtering data.
GetFriction Gets the shape's friction coefficient, usually in the range [0,1].
GetRestitution Gets the shape's restitution (elasticity) usually in the range [0,1].
IsSensor Returns True if this shape is a sensor.
SetDensity Sets the shape's density, usually in kg/m^2.
SetFilter Sets the contact filtering data.
SetFriction Sets the shape's friction coefficient, usually in the range [0,1].
SetIsSensor A sensor shape collects contact information but never generates a collision response.
SetRestitution Sets the shape's restitution (elasticity) usually in the range [0,1].
SetUserData Sets the user data.
Method GetDensity:Float()
DescriptionGets the shape's density, usually in kg/m^2.
Method GetFilter:b2FilterData()
DescriptionReturns the contact filtering data.
Method GetFriction:Float()
DescriptionGets the shape's friction coefficient, usually in the range [0,1].
Method GetRestitution:Float()
DescriptionGets the shape's restitution (elasticity) usually in the range [0,1].
Method IsSensor:Int()
DescriptionReturns True if this shape is a sensor.
InformationA sensor shape collects contact information but never generates a collision response.
Method SetDensity(density:Float)
DescriptionSets the shape's density, usually in kg/m^2.
Method SetFilter(filter:b2FilterData)
DescriptionSets the contact filtering data.
Method SetFriction(friction:Float)
DescriptionSets the shape's friction coefficient, usually in the range [0,1].
Method SetIsSensor(sensor:Int)
DescriptionA sensor shape collects contact information but never generates a collision response.
Method SetRestitution(restitution:Float)
DescriptionSets the shape's restitution (elasticity) usually in the range [0,1].
Method SetUserData(data:Object)
DescriptionSets the user data.

Type b2TensorDampingController Extends b2Controller
DescriptionApplies top down linear damping to the controlled bodies.
InformationThe damping is calculated by multiplying velocity by a matrix in local co-ordinates.
Methods Summary
GetMaxTimestep Returns the maximum amount of damping.
GetTensor Returns the tensor to use in damping model.
SetMaxTimestep Set this to a positive number to clamp the maximum amount of damping done.
SetTensor Sets the tensor to use in damping model.
Method GetMaxTimestep:Float()
DescriptionReturns the maximum amount of damping.
Method GetTensor:b2Mat22()
DescriptionReturns the tensor to use in damping model.
Method SetMaxTimestep(timestep:Float)
DescriptionSet this to a positive number to clamp the maximum amount of damping done.
Method SetTensor(tensor:b2Mat22)
DescriptionSets the tensor to use in damping model.
InformationSome examples (matrixes in format (row1; row2) )
MatrixDescription
(-a 0;0 -a)Standard isotropic damping with strength a
(0 a;-a 0)Electron in fixed field - a force at right angles to velocity with proportional magnitude
(-a 0;0 -b)Differing x and y damping. Useful e.g. for top-down wheels.

By the way, tensor in this case just means matrix, don't let the terminology get you down.


Type b2TensorDampingControllerDef Extends b2ControllerDef
DescriptionUsed to build tensor damping controllers.
Methods Summary
GetMaxTimestep Returns the maximum amount of damping.
GetTensor Returns the tensor to use in damping model.
SetAxisAligned Sets damping independently along the x and y axes.
SetMaxTimestep Set this to a positive number to clamp the maximum amount of damping done.
SetTensor Sets the tensor to use in damping model.
Method GetMaxTimestep:Float()
DescriptionReturns the maximum amount of damping.
Method GetTensor:b2Mat22()
DescriptionReturns the tensor to use in damping model.
Method SetAxisAligned(xDamping:Float, yDamping:Float)
DescriptionSets damping independently along the x and y axes.
Method SetMaxTimestep(timestep:Float)
DescriptionSet this to a positive number to clamp the maximum amount of damping done.
Method SetTensor(tensor:b2Mat22)
DescriptionSets the tensor to use in damping model.
InformationSome examples (matrixes in format (row1; row2) )
MatrixDescription
(-a 0;0 -a)Standard isotropic damping with strength a
(0 a;-a 0)Electron in fixed field - a force at right angles to velocity with proportional magnitude
(-a 0;0 -b)Differing x and y damping. Useful e.g. for top-down wheels.

By the way, tensor in this case just means matrix, don't let the terminology get you down.


Type b2Vec2
DescriptionA 2D column vector.
Globals Summary
ZERO
Methods Summary
Add Adds vec to this vector.
Copy Copies vec into this object.
Create Creates a new vector with the given coordinates.
Divide Divides the vector by value.
GetX Returns the X coordinate.
GetY Returns the Y coordinate.
Length Returns the length of this vector.
LengthSquared Get the length squared.
Multiply Multiplies the vector by value.
Normalize Convert this vector into a unit vector.
Plus Adds vec to this vector, returning the a new b2Vec2.
Set Sets the x and y parts.
Subtract Subtracts vec from this object, returning a new b2Vec2.
X Returns the X coordinate.
Y Returns the Y coordinate.
Functions Summary
CreateVec2 Creates a new vector with the given coordinates.
Global ZERO:b2Vec2
DescriptionA zero vector (0,0)
Method Add(vec:b2Vec2)
DescriptionAdds vec to this vector.
Method Copy(vec:b2Vec2)
DescriptionCopies vec into this object.
Method Create:b2Vec2(x:Float = 0, y:Float = 0)
DescriptionCreates a new vector with the given coordinates.
Method Divide:b2Vec2(value:Float)
DescriptionDivides the vector by value.
Method GetX:Float()
DescriptionReturns the X coordinate.
Method GetY:Float()
DescriptionReturns the Y coordinate.
Method Length:Float()
DescriptionReturns the length of this vector.
Method LengthSquared:Float()
DescriptionGet the length squared.
InformationFor performance, use this instead of b2Vec2::Length (if possible).
Method Multiply:b2Vec2(value:Float)
DescriptionMultiplies the vector by value.
Method Normalize:Float()
ReturnsThe length.
DescriptionConvert this vector into a unit vector.
Method Plus:b2Vec2(vec:b2Vec2)
DescriptionAdds vec to this vector, returning the a new b2Vec2.
InformationThis object is not modified.
Method Set(x:Float, y:Float)
DescriptionSets the x and y parts.
Method Subtract:b2Vec2(vec:b2Vec2)
DescriptionSubtracts vec from this object, returning a new b2Vec2.
InformationThis object is not modified.
Method X:Float()
DescriptionReturns the X coordinate.
Method Y:Float()
DescriptionReturns the Y coordinate.
Function CreateVec2:b2Vec2(x:Float = 0, y:Float = 0)
DescriptionCreates a new vector with the given coordinates.

Type b2World
DescriptionThe world type manages all physics entities, dynamic simulation, and asynchronous queries.
InformationThe world also contains efficient memory management facilities.
Methods Summary
Create Construct a world object.
CreateBody Create a rigid body given a definition.
CreateController Add a controller to the world.
CreateJoint Create a joint to constrain bodies together.
DestroyBody Destroy a rigid body given a definition.
DestroyController Removes a controller from the world.
DestroyJoint Destroy a joint.
DoStep Take a time Step.
GetBodyCount Get the number of bodies.
GetBodyList Get the world body list.
GetGroundBody The world provides a single static ground body with no collision shapes.
GetJointCount Get the number joints.
GetJointList Get the world joint list.
GetPairCount Get the number of broad-phase pairs.
GetProxyCount Get the number of broad-phase proxies.
InRange Check if the AABB is within the broadphase limits.
Query Query the world for all shapes that potentially overlap the provided AABB.
Raycast Query the world for all shapes that intersect a given segment.
RaycastOne Performs a raycast as with Raycast, finding the first intersecting shape.
Refilter Re-filter a shape.
SetBoundaryListener Register a broad-phase boundary listener.
SetContactListener Register a contact event listener.
SetContinuousPhysics Enable/disable continuous physics. For testing.
SetDebugDraw Register a routine for debug drawing.
SetDestructionListener Register a destruction listener.
SetFilter Register a contact filter to provide specific control over collision.
SetGravity Change the global gravity vector.
SetWarmStarting Enable/disable warm starting. For testing.
Validate Perform validation of internal data structures.
Functions Summary
CreateWorld Construct a world object.
Method Create:b2World(worldAABB:b2AABB, gravity:b2Vec2, doSleep:Int)
DescriptionConstruct a world object.
Method CreateBody:b2Body(def:b2BodyDef)
DescriptionCreate a rigid body given a definition.
InformationNo reference to the definition is retained.

Warning: This method is locked during callbacks.

Method CreateController:b2Controller(def:b2ControllerDef)
DescriptionAdd a controller to the world.
Method CreateJoint:b2Joint(def:b2JointDef)
DescriptionCreate a joint to constrain bodies together.
InformationNo reference to the definition is retained. This may cause the connected bodies to cease colliding.

Warning: This method is locked during callbacks.

Method DestroyBody(body:b2Body)
DescriptionDestroy a rigid body given a definition.
InformationNo reference to the definition is retained.

Warning: This automatically deletes all associated shapes and joints.

Warning: This method is locked during callbacks.

Method DestroyController(controller:b2Controller)
DescriptionRemoves a controller from the world.
Method DestroyJoint(joint:b2Joint)
DescriptionDestroy a joint.
InformationThis may cause the connected bodies to begin colliding.

Warning: This method is locked during callbacks.

Method DoStep(timeStep:Float, velocityIterations:Int, positionIterations:Int)
DescriptionTake a time Step.
InformationThis performs collision detection, integration, and constraint solution.

Parameters:

  • timeStep : the amount of time To simulate, this should Not vary.
  • velocityIterations : for the velocity constraint solver.
  • positionIterations : for the position constraint solver.

Method GetBodyCount:Int()
DescriptionGet the number of bodies.
Method GetBodyList:b2Body()
ReturnsThe head of the world body list.
DescriptionGet the world body list.
InformationWith the returned body, use b2Body::GetNext to get the next body in the world list. A NULL body indicates the end of the list.
Method GetGroundBody:b2Body()
DescriptionThe world provides a single static ground body with no collision shapes.
InformationYou can use this to simplify the creation of joints and static shapes.
Method GetJointCount:Int()
DescriptionGet the number joints.
Method GetJointList:b2Joint()
ReturnsThe head of the world joint list.
DescriptionGet the world joint list.
InformationWith the returned joint, use b2Joint::GetNext to get the next joint in the world list. A NULL joint indicates the end of the list.
Method GetPairCount:Int()
DescriptionGet the number of broad-phase pairs.
Method GetProxyCount:Int()
DescriptionGet the number of broad-phase proxies.
Method InRange:Int(aabb:b2AABB)
DescriptionCheck if the AABB is within the broadphase limits.
Method Query:Int(aabb:b2AABB, shapes:b2Shape[])
ReturnsThe number of shapes found in aabb.
DescriptionQuery the world for all shapes that potentially overlap the provided AABB.
InformationYou provide a shape array for populating. The number of shapes found is returned.
Method Raycast:Int(segment:b2Segment, shapes:b2Shape[], solidShapes:Int)
DescriptionQuery the world for all shapes that intersect a given segment.
InformationYou provide a shape array of an appropriate size. The number of shapes found is returned, and the array is filled in order of intersection.
Method RaycastOne:b2Shape(segment:b2Segment, lambda:Float Var, normal:b2Vec2, solidShapes:Int)
DescriptionPerforms a raycast as with Raycast, finding the first intersecting shape.
Method Refilter(shape:b2Shape)
DescriptionRe-filter a shape.
InformationThis re-runs contact filtering on a shape.
Method SetBoundaryListener(listener:b2BoundaryListener)
DescriptionRegister a broad-phase boundary listener.
Method SetContactListener(listener:b2ContactListener)
DescriptionRegister a contact event listener.
Method SetContinuousPhysics(flag:Int)
DescriptionEnable/disable continuous physics. For testing.
Method SetDebugDraw(debugDraw:b2DebugDraw)
DescriptionRegister a routine for debug drawing.
InformationThe debug draw functions are called inside the b2World::DoStep method, so make sure your renderer is ready to consume draw commands when you call DoStep().
Method SetDestructionListener(listener:b2DestructionListener)
DescriptionRegister a destruction listener.
Method SetFilter(_filter:b2ContactFilter)
DescriptionRegister a contact filter to provide specific control over collision.
InformationOtherwise the default filter is used.
Method SetGravity(gravity:b2Vec2)
DescriptionChange the global gravity vector.
Method SetWarmStarting(flag:Int)
DescriptionEnable/disable warm starting. For testing.
Method Validate()
DescriptionPerform validation of internal data structures.
Function CreateWorld:b2World(worldAABB:b2AABB, gravity:b2Vec2, doSleep:Int)
DescriptionConstruct a world object.

Type b2XForm
DescriptionA transform contains translation and rotation.
InformationIt is used to represent the position and orientation of rigid frames.
Methods Summary
Create  
GetPosition  
GetR  
SetPosition  
SetR  
Method Create:b2XForm()
Method GetPosition:b2Vec2()
Method GetR:b2Mat22()
Method SetPosition(pos:b2Vec2)
Method SetR(r:b2Mat22)

Module Information

Version1.04
LicenseMIT
CopyrightBox2D (c) 2006-2008 Erin Catto http://www.gphysics.com
CopyrightBlitzMax port - 2008-2009 Bruce A Henderson
History1.04
HistoryUpdated to box2d svn (rev 207)
HistoryAdded b2LineJoint type.
HistoryAdded b2ShapeDef.SetUserData() method.
HistoryAdded b2Mat22.GetAngle() method.
HistoryAdded b2Mat22 Create... methods, and others.
HistoryAdded shape SetFriction() and SetRestitution() methods.
HistoryFixed contact filter example and docs.
HistoryAdded b2EdgeShape type.
HistoryAdded staticedges, dynamicedges, pyramidstaticedges and buoyancy examples.
HistoryAdded buoyancy types + methods.
HistoryAdded b2Body SetMass() method.
HistoryAdded b2BodyDef GetMassData() method.
HistoryConverted bool handling in glue to use ints instead.
History1.03
HistoryUpdated to box2d svn (rev 172)
HistoryAdded b2CircleShape and b2PolygonShape types.
HistoryAdded b2OBB type.
HistoryAdded b2Segment type.
HistoryAdded b2World Raycast(), RaycastOne() and InRange() methods.
HistoryAdded b2Body.GetWorld() method.
HistoryAdded raycast example.
History1.02
HistoryUpdated to box2d svn (rev 169)
HistoryAPI CHANGES : DoStep() - changed iteration parameters
HistoryAPI CHANGES : joints - GetReactionForce() And GetReactionTorque() added 'dt' parameter.
HistoryAdded car example.
HistoryAdded revolute example.
HistoryAdded b2ShapeDef - SetIsSensor and IsSensor methods.
HistoryFixed typo in b2ContactListener - Remove().
HistoryAdded b2World.Refilter() and several missing b2Shape methods.
HistoryUpdated Documentation.
History1.01
HistoryFixed filterdata problem. Fixed collisionfiltering example.
HistoryAdded Theo Jansen example.
History1.00 Initial Release