b2World Class
The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient memory management facilities.
Item Index
Methods
- this constructor
- clearForces
- createBody
- createDistanceJoint
- createFrictionJoint
- createGearJoint
- createLineJoint
- createMouseJoint
- createPrismaticJoint
- createPulleyJoint
- createRevoluteJoint
- destroyBody
- destroyJoint
- doDebugDraw
- doDraw
- getBodyCount
- getContactCount
- getGravity
- getJointCount
- getProxyCount
- setContinuousPhysics
- setGravity
- setWarmStarting
- step
Properties
Events
Methods
this
[xGravity=0]
[yGravity=9.8]
[doSleep]
[enableCollisions]
Construct a world object.
Parameters:
Example:
var app = new Moscrif.Window(); app.terminate = false; app.onStart = function() { // create world this._world = new b2World(0.0, -9.8);
// load image, which should be drawen into the body
var bodyImg = Bitmap.fromFile("app://img.png");
// create shape of body
var shape = b2PolygonShape.fromRect(bodyImg.width, bodyImg.height);
// create body
var body = this._world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
// draw body
body.onDraw = function(sender, canvas)
{
var (l, t) = this.getPosition();
canvas.drawBitmap(bodyImg, l.toInteger(), t.toInteger());
}
}
app.onProcess = function(sender) { // recalculate world this._world.step(1.0/40.0, 4, 8); // redraw window this.invalidate(); return this.terminate ? 0 : 1; }
app.onDraw = function(sender, canvas) { // clear body canvas.clear(0xff000000); // draw b2 world this._world.doDraw(canvas); }
app.init().run();
clearForces
()
Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step.
createBody
b2CircleShape
bodyTypeSym
[density=1]
[friction=0.3]
[bounce=0.2]
[x=0.0]
[y=0.0]
Create new box2d body and place it to the x, y.
Parameters:
-
b2CircleShape
B2CircleShapeShape of new object.
-
bodyTypeSym
SymbolBodyType's parameter .
- #static - A static body has does not move under simulation and behaves as if it has infinite mass. Internally, Box2D stores zero for the mass and the inverse mass. Static bodies can be moved manually by the user. A static body has zero velocity. Static bodies do not collide with other static or kinematic bodies.
- #dynamic - A dynamic body is fully simulated. They can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass. If you try to set the mass of a dynamic body to zero, it will automatically acquire a mass of one kilogram.
- #kinematic - A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces. They can be moved manually by the user, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass. Kinematic bodies do not collide with other static or kinematic bodies.
-
[density=1]
Float optionalDensity 0 to 1.
-
[friction=0.3]
Float optionalFriction 0 to 1.
-
[bounce=0.2]
Float optionalBounce 0 to 1.
-
[x=0.0]
Integer optionalPosition of object on x axis.
-
[y=0.0]
Integer optionalPosition of object on y axis.
Returns:
createDistanceJoint
bodyA
bodyB
anchorXA
anchorYA
anchorXB
anchorYB
scriptDef
[collideConnected]
Create distance joint between two objects. Distance joints says that the distance between two points on two bodies must be constant.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
anchorXA
FloatX position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.
-
anchorYA
FloatY position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.
-
anchorXB
FloatX position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.
-
anchorYB
FloatY position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.
-
scriptDef
ArrayOther joints properties:
- distanceLength - Default length between bodies (between anchor points).
- frequencyHz - The mass-spring-damper frequency in Hertz. A value of 0 disables softness.
- dampingRatio - The damping ratio from 0 to 1.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
Example:
this.bodyA = this.world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
this.bodyB = this.world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
var def =
{
dampingRatio: 0.5; //from 0 to 1
};
var (xa, ya) = this.bodyA.getWorldCenter();
var (xb, yb) = this.bodyB.getWorldCenter();
this.joint = this.world.createDistanceJoint(this.bodyA, this.bodyB, xa, ya, xb, yb, def);
createFrictionJoint
bodyA
bodyB
anchorX
anchorY
scriptDef
[collideConnected]
The friction joint is used for top-down friction. The joint provides 2D translational friction and angular friction.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
anchorX
FloatX position of anchor point.
-
anchorY
FloatY position of anchor point.
-
scriptDef
ArrayOther joints properties:
- maxForce - The maximum friction force in N.
- maxTorque - The maximum friction torque in N-m.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
createGearJoint
bodyA
bodyB
jojnt1
jojnt2
ratio
[collideConnected]
If you want to create a sophisticated mechanical contraption you might want to use gears. Gear joint connects two other types of joints and move them with set ratio.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
jojnt1
FloatFirst joint.
-
jojnt2
FloatSecond joint.
-
ratio
FloatRatio between both joints.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
createLineJoint
bodyA
bodyB
anchorX
anchorY
axisX
axisY
referenceAngle
scriptDef
[collideConnected]
This joint provides two degrees of freedom: translation along an axis fixed in body1 and rotation in the plane. 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.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
anchorX
FloatX position of anchor point. Anchor point is point on the body, which is conected with the second body.
-
anchorY
FloatY position of anchor point. Anchor point is point on the body, which is conected with the second body.
-
axisX
FloatX coordinate of axis.
-
axisY
FloatY coordinate of axis.
-
referenceAngle
FloatReferenceAngle angle
-
scriptDef
ArrayOther joints properties:
- lowerTranslation - The lower translation limit, usually in meters.
- upperTranslation - The upper translation limit, usually in meters.
- enableLimit - Enable/disable the joint limit.
- maxMotorForce - The maximum motor torque, usually in N-m.
- motorSpeed - The desired motor speed in radians per second.
- enableMotor - Enable/disable the joint motor.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
createMouseJoint
bodyA
bodyB
scriptDef
[collideConnected]
A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
scriptDef
ArrayOther joints properties:
- maxForce - The maximum constraint force that can be exerted to move the candidate body. Usually you will express as some multiple of the weight (multiplier * mass * gravity).
- frequencyHz - The response speed.
- dampingRatio - The damping ratio. 0 = no damping, 1 = critical damping.
- targetX - X coordinate of initial world target point. This is assumed to coincide with the body anchor initially.
- targetY - Y coordinate of initial world target point. This is assumed to coincide with the body anchor initially.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
Example:
var b2x = x / this._world.scale;
var b2y = (System.height-y) / this._world.scale;
var mouseJointDef = {
maxForce : 2500,
frequencyHz : 10000,
dampingRatio : 0.0,
targetX : b2x,
targetY : b2y
};
// crate mouse joint
this._mouseJoint = this._world.createMouseJoint(this._ground, body, mouseJointDef, true);
createPrismaticJoint
bodyA
bodyB
anchorX
anchorY
axisX
axisY
referenceAngle
scriptDef
[collideConnected]
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.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
anchorX
FloatX position of anchor point. Anchor point is point on the body, which is conected with the second body.
-
anchorY
FloatY position of anchor point. Anchor point is point on the body, which is conected with the second body.
-
axisX
FloatX coordinate of axis.
-
axisY
FloatY coordinate of axis.
-
referenceAngle
FloatReferenceAngle angle
-
scriptDef
ArrayOther joints properties:
- lowerTranslation - The lower translation limit, usually in meters.
- upperTranslation - The upper translation limit, usually in meters.
- enableLimit - Enable/disable the joint limit.
- maxMotorForce - The maximum motor torque, usually in N-m.
- motorSpeed - The desired motor speed in radians per second.
- enableMotor - Enable/disable the joint motor.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
createPulleyJoint
bodyA
bodyB
groundAnchorAX
groundAnchorAY
groundAnchorBX
groundAnchorBY
anchorAX
anchorAY
anchorBX
anchorBY
ratio
[collideConnected]
The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio * length2 <= constant Yes, the force transmitted is scaled by the ratio.
Warning: the pulley joint can get a bit squirrelly by itself. They often work better when combined with prismatic joints. You should also cover the the anchor points with static shapes to prevent one side from going to zero length.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
groundAnchorAX
FloatX coordinatesof of the first ground anchor.
-
groundAnchorAY
FloatY coordinatesof of the first ground anchor.
-
groundAnchorBX
FloatX coordinatesof of the second ground anchor.
-
groundAnchorBY
FloatY coordinatesof of the second ground anchor.
-
anchorAX
FloatX world coordinate of the anchor point on bodyA.
-
anchorAY
FloatY world coordinate of the anchor point on bodyA.
-
anchorBX
FloatX world coordinate of the anchor point on bodyB.
-
anchorBY
FloatY world coordinate of the anchor point on bodyB.
-
ratio
FloatThe pulley ratio.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
createRevoluteJoint
bodyA
bodyB
anchorX
anchorY
scriptDef
[collideConnected]
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.
Parameters:
-
bodyA
B2BodyFirst body.
-
bodyB
B2BodySecond body.
-
anchorX
FloatX position of anchor point. Anchor point is point around which bodies are rotated.
-
anchorY
FloatY position of anchor point. Anchor point is point around which bodies are rotated.
-
scriptDef
ArrayOther joints properties (A joint limit forces the joint angle to remain between a lower and upper bound. The limit range should include zero, otherwise the joint will lurch when the simulation begins. Angle is positive when rotates CCW.)
- lowerAngle - The lower angle for the joint limit (radians).
- upperAngle - The upper angle for the joint limit (radians).
- enableLimit - True/false to enable joint limits.
- maxMotorTorque - The maximum motor torque used to achieve the desired motor speed. Usually in N-m.
- motorSpeed - The desired motor speed. Usually in radians per second.
- enableMotor - True / false to enable the joint motor.
-
[collideConnected]
Boolean optionalIf this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.
Returns:
Example:
//properties like: enableLimit, lowerAngle, enableMotor etc.
var def =
{
enableLimit: true;
...
};
var joint = this.world.createRevoluteJoint(bodyA, bodyB, x, y, def);
destroyBody
body
Destroy existing physics body. WARNING: The bodies should not be removed in PhysicsScene/onBeginContact and PhysicsScene/onEndContact. Probably the better way is to remove it in Game/onProcess event.
Parameters:
-
body
B2BodyBody to destroy.
Example:
this.body = this.world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
....
// destroy body
this.world.destroyBody(this.body);
destroyJoint
joint
Destroy a joint. WARNING: The joints should not be removed in PhysicsScene/onBeginContact and PhysicsScene/onEndContact. Probably the better way is to remove it in Game/onProcess event.
Parameters:
-
joint
B2JointJoint to destroy.
Example:
this.joint = this.world.createDistanceJoint(body, bodyB, xa, ya, xb, yb, def);
...
// destroy joint before closing the application
this.world.destroyJoint(this.joint);
doDebugDraw
canvas
Call this to draw shapes and other debug draw data.
Parameters:
-
canvas
IntegerInstance of canvas class into which world should be drawn.
Example:
var app = new Moscrif.Window();
app.terminate = false;
....onStart = function()
{
// create world
this._world = new b2World();
}
....onDraw = function(sender, canvas)
{
// clear body
canvas.clear(0xff000000);
// draw b2 world
this._world.doDebugDraw(canvas);
}
app.init().run();
doDraw
canvas
Call this to redraw all objects in the world.
Parameters:
-
canvas
IntegerInstance of canvas class into which world should be drawn.
Example:
var app = new Moscrif.Window();
app.terminate = false;
....onStart = function()
{
// create world
this._world = new b2World();
}
....onDraw = function(sender, canvas)
{
// clear body
canvas.clear(0xff000000);
// draw b2 world
this._world.doDraw(canvas);
}
app.init().run();
getBodyCount
() Integer
Get the number of bodies.
Returns:
Example:
// create world
this._world = new b2World();
// change gravity additionaly
var shape = b2PolygonShape.fromRect(50, 20);
// create body
var bodies = new Array();
var bodyCount = 4;
for (var i = 0; i < bodyCount; i++) {
bodies[i] = this._world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
// draw body
bodies[i].onDraw = function(sender, canvas)
{
...
}
}
// body count: 4
console<<"body count: "<<this._world.getBodyCount()<<"\n";
getContactCount
() Integer
Get the number of contacts (each may have 0 or more contact points).
Returns:
Example:
if (this.world.getContactCount () > 0)
console<<"two or more bodies colide together\n";
else
console<<"no colisions in world\n";
getGravity
() Multivalue
Get the global gravity.
Returns:
Example:
this.world = new b2World();
// get world's gravity (default gravity)
var (gx, gy) = this.world.getGravity();
// gx is now 0.0 and gy 9.8
getProxyCount
() Integer
Get the number of broad-phase proxies.
Returns:
setContinuousPhysics
flag
Enable/disable continuous physics. For testing. Continuous collision detection (also called CCD), is a box2d feature which ensures correct simulation of fast moving objects. Some older physical engines do not supports CCD, what means that they calculate positions and colisions of bodies for every time step, what is called discrete simulation. However in discrete simulation rigid body can move long distance in time step. (If the body has sufficiently high speed, it can be before time step few meters in front of the barrier and after time step it can be few meters behind the barrier.) It caused that the fast moving body can move throw another body without detection of collision between these two bodies. This effect is called tunneling. By default box2d uses CCD to prevent tunneling effect. CCD looks for all collisions between the position before and after time step. For every collision it calculates time of impact (TOI). On the next time step the body moves only to the next TOI and then wait for the rest of time step and does not move anymore during the time step. To ensure the best performace the CCD calculates contacts only between dynamic and static bodies (not between the dynamic bodies each other). However, onto dynamic bodies can be set CCD separately. If there is fast moving body, which hit other dynamic bodies, you can set the fast moving body’s property bullet to true to allows CCD onto it.
Parameters:
-
flag
BooleanTrue / false to enable / disable.
setGravity
gx
gy
Set world’s gravity (separately for x and y axis).
Example:
// create world
this._world = new b2World();
// change gravity additionally
this._world.setGravity(0.0, 9.8);
setWarmStarting
flag
Enable/disable warm starting. If the warm starting is enabled some box2d solvers uses resoul from previous time step, what improves performance.
Parameters:
-
flag
BooleanTrue / false to enable / disable.
step
[timeStep]
[velocityIterations]
[positionIterations]
Take a time step. This performs collision detection, integration, and constraint solution.
Parameters:
Example:
....
....onStart = function()
{
// create world
this._world = new b2World(0.0, -9.8);
...
// create body
var body = this._world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
....
}
....onProcess = function(sender)
{
// recalculate world
this._world.step(1.0/40.0, 4, 8);
// redraw window
this.invalidate();
return this.terminate ? 0 : 1;
}
Properties
autoClearForces
Boolean
Flag to control automatic clearing of forces after each time step. By default it is set to true.
scale
Float
Value represent scale of box2d world against screen resolution. The width of the physics world is always 10 meters. I means that on different displays the world is scaled diferently. The scale property says how meny pixels on the screens represents one meter in physical simulation. It helps to convert screen coordinates to box2d coordinates, which also do not start from the left top corner as a screen pixels coordinates, but from the left bottom corner of the screen.
Example:
// converts x-coord from screen to box2d
function x2box2d(x)
{
return x / this._world.scale;
}
// converts y-coord from screen to box2d
function y2box2d(y)
{
return (System.height - y) / this._world.scale;
}
Events
onBeginContact
This function is called, when two bodies collide.
Event Payload:
-
sender
B2WorldObject, which called this function.
-
contact
B2ContactInstance of b2Contact contains all informations about contact.
Example:
this.world.onBeginContact = function(sender, contact)
{
// manage contact
var bodyA = current.getBodyA();
var bodyB = current.getBodyB();
...
};
onEndContact
This function is called, when contact ends.
Event Payload:
-
sender
B2WorldObject, which called this function.
-
contact
B2ContactInstance of b2Contact contains all informations about contact.
Example:
this.world.onEndContact = function(sender, contact)
{
// manage contact
var bodyA = current.getBodyA();
var bodyB = current.getBodyB();
...
};