PhysicsScene Class
This class manages creates background for all physical entities like physical sprites, joints or contacts. It also sets basic hysical properties properties like gravity and provides time steps in simulation. The class contains an instance of native b2World class, which provides all calculations on background.
Example:
// create instance of physics scene (create method aoutomatically create an instance of b2World class)
var scene = PhysicsScene.create(0.0, -0.5);
// OR
// create an instance of b2World class manually in init function of extended class
class GameScene : PhysicsScene
{
function init()
{
super.init();
// create physics world
this.world = new b2World(0.0, -9.8, true, false);
...
}
...
}
// then instance of GameScene can be creates simply by key word new
var scene = new GameScene();
Item Index
Methods
- addCircleBody
- addEdgeBody
- addPolygonBody
- beginContact
- clearForces
- create
- createDistanceJoint
- createFrictionJoint
- createGearJoint
- createLineJoint
- createMouseJoint
- createPrismaticJoint
- createPulleyJoint
- createRevoluteJoint
- createWeldJoint
- destroyBody
- destroyJoint
- doDebugDraw
- draw
- endContact
- getBody
- getBodyCount
- getContactCount
- getGravity
- getJointCount
- getProxyCount
- init
- setContinuousPhysics
- setGravity
- setWarmStarting
- step
Properties
Events
Methods
addCircleBody
image
bodyTypeSym
density
friction
bounce
radius
Add circle physics sprite.
Parameters:
-
image
Bitmap -
bodyTypeSym
Symbol#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
FloatDensity of the sprite.
-
friction
FloatFriction of the sprite, affects the body adhesion.
-
bounce
FloatThe bounce 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. If collide two bodies with different bounce the box2d uses larger value to simulate the bounce.
-
radius
FloatRadius of circle body. The radius should be same as a radious of an image, because the image drawen in the body is not limited by the sprites's shape.
Returns:
Example:
var puck = this.addCircleBody(res.images.puck, #dynamic, density, friction, bounce, res.images.puck.width / 2);
// place puck to center of the table
puck.setPosition(System.width / 2, System.height / 2);
addEdgeBody
image
bodyTypeSym
density
friction
bounce
v1x
v1y
v2x
v2y
Add edge physics sprite into scene. Edge shapes are line segments. These are provided to assist in making a free-form static environment. Edge shapes can collide with circles and polygons bodies but not with themselves. Edge bodies have no volume.
Parameters:
-
image
BitmapImage drawn in the body
-
bodyTypeSym
Symbol#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
FloatDensity of the sprite.
-
friction
FloatFriction of the sprite, affects the body adhesion.
-
bounce
FloatThe bounce 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. If collide two bodies with different bounce the box2d uses larger value to simulate the bounce.
-
v1x
FloatX coordinate of the first point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.
-
v1y
FloatY coordinate of the first point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.
-
v2x
FloatX coordinate of the second point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.
-
v2y
FloatY coordinate of the second point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.
Returns:
Example:
var ground = Bitmap.fromFile("app://ground.png");
var sprite = this.addEdgeBody(ground, #static, 0.0, 0.0, 0.0, ground.width / -2, 1, ground.width / 2, 10)
sprite.setPosition(System.width / 2, System.height/2);
addPolygonBody
image
bodyTypeSym
density
friction
bounce
width/array
height
Add polygon physics sprite into scene.
Parameters:
-
image
BitmapImage drawn in the body
-
bodyTypeSym
Symbol#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
FloatDensity of the sprite.
-
friction
FloatFriction of the sprite, affects the body adhesion.
-
bounce
FloatThe bounce 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. If collide two bodies with different bounce the box2d uses larger value to simulate the bounce.
-
width/array
Integer/ArrayWidth of polygon body in pixels or array of vectors. If the value is integer typical rectangle body is created. If it is an array a polygon body is created and last parameter is ignored. The array should contains objects with two values: x and y -> distance from center in pixels (positive values are located up and right). Points in array should by in CCW order. Minimum number of vertex are 3 maximum (ussally) 8.
-
height
IntegerHeight of polygon body in pixels. The sprite height should be same as a height of image, otherwise the image will be drawen outside (or innear) real body shape. The image is not limited by sprite width or height.
Returns:
Example:
// create rectangle body
var ramp = Bitmap.fromFile("app://ramp.png");
var body = this.addPolygonBody(ramp, #static, 1.0, 1.0, 0.0, ramp.width, ramp.height);
body.setPosition(System.width / 2, System.height);
// create triangle body
var shape = new Array(
// top - left
{x : width /-2, y : height / 2},
// bottom - left
{x : width /-2, y : height / -2},
// bottom - right
{x : width /2, y : height / -2}
)
// create triangle body
var body = this._world.addPolygonBody(imgBox, #dynamic, 0.9 , 0.0, 0.0, shape);
beginContact
PhysicsContact
beginContact function is called as a reaction on the onBeginContact event. This event is called when two bodies collide.
Parameters:
-
PhysicsContact
ObjectList of all contacts which appeared in last time step.
Example:
function beginContact(contact)
{
// get the first contact
var current = contact;
while (current) {
// get the bodies in the contact
var bodyA = current.getBodyA();
var bodyB = current.getBodyB();
...
// get the next contact (they can be more contacts during the one step)
current = current.getNext();
}
}
clearForces
()
Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to step method.
create
gx
gy
options
Create an instance of box2d body. Using the create function ensures that native b2World object will be automatically created and it is not needed to create it manually in init method.
Parameters:
-
gx
Floatcomponent of the world gravity vector on the x-axis
-
gy
Floatcomponent of the world gravity vector on the y-axis
-
options
Objectsleep Boolean If the sleeping is allowed inactive bodies are not simulated, what improves performance. Default is sleeping disabled. enableCollisions Boolean Enable collisions between bodies. By defeault they are allowed. calledClass Class The called class, default is PhysicsScene.
Example:
// create instance of physics scene (create method aoutomatically create an instance of b2World class)
var scene = PhysicsScene.create(0.0, -0.5, { calledClass: GameScene } );
createDistanceJoint
bodyA
bodyB
anchorAx
anchorAy
Float
anchorBy
jointDef
collideConnected
Create distance joint between two objects. Distance joints says that the distance between two points on two bodies must be constant.
Parameters:
-
bodyA
PhysicsBodyfirst connected body
-
bodyB
PhysicsBodysecond connected body
-
anchorAx
FloatX position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.
-
anchorAy
FloatY position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.
-
Float
ObjectanchorBx X position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.
-
anchorBy
FloatY position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.
-
jointDef
ObjectOther 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
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// create the distance joint
var jointDef = {
frequencyHz : 100,
dampingRatio : 0.0,
// distanceLength : use default distance (distance which was between the bodies when they were created
}
this._distanceJoint = this.createDistanceJoint(this._rect1, this._rect2, System.width / 2,System.height / 2,System.width / 2,3*System.height / 4, jointDef, false)
createFrictionJoint
bodyA
bpdyB
x
y
jointDef
collideConnected
The friction joint is used for top-down friction. The joint provides 2D translational friction and angular friction.
Parameters:
-
bodyA
PhysicsBodyfirst connected body
-
bpdyB
PhysicsBodysecond connected body
-
x
FloatX position of anchor point.
-
y
FloatY position of anchor point.
-
jointDef
ObjectOther joints properties: maxForce - The maximum friction force in N. maxTorque - The maximum friction torque in N-m.
-
collideConnected
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
createGearJoint
bodyA
bodyB
joint1
joint2
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
PhysicsBodyfirst connected body
-
bodyB
PhysicsBodysecond connected body
-
joint1
B2JointFirst connected joint
-
joint2
B2JointSecond connected joint
-
ratio
Object{Float] Ratio between the joints motion. Ratio 1.0 means that both joint move same distance (speed).
-
collideConnected
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// create the prismatic joint
// set limits
var jointDef = {
...
}
var prismaticJoint = this.createPrismaticJoint(this._leftWall, this._rect2, System.width / 2, System.height / 5, 0.0, 1.0, 0.0, jointDef, true)
// create the revolute joint
jointDef = {
...
}
// create joint
var revoluteJoint = this.createRevoluteJoint(this._ground, this._rect1, System.width / 2, System.height / 5, jointDef, true);
// connect bodies with gear joint
this._gearJoint = this.createGearJoint(this._rect1, this._rect2, prismaticJoint, revoluteJoint, 0.8, true);
createLineJoint
bodyA
bodyB
anchorX
anchorY
axisX
axisY
referenceAngle
jointDef
collideConnected
This joint provides two degrees of freedom: translation along an axis fixed in body1 and rotation in the plane.
Parameters:
-
bodyA
PhysicsBodyfirst connected body
-
bodyB
PhysicsBodysecond connected 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
Floatreference Angle
-
jointDef
ObjectOther 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
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
createMouseJoint
PhysicsBody
PhysicsBody
Array
Boolean
A mouse joint is used to make a point on a body track a specified world point. It is usually used to track user finger on the screen.
Parameters:
-
PhysicsBody
ObjectFirst body in joint, also called as a ground body. This body is is not important it can be also body with zero width and height placed anywhere in the scene.
-
PhysicsBody
ObjectBody, which chould track a pointer
-
Array
ObjectjointDef Other 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.
-
Boolean
ObjectcollideConnected If this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// mouse joint definition
var mouseJointDef = {
maxForce : 10000,
frequencyHz : 1000,
dampingRatio : 0.0,
targetX : table.x2box2d(x), // specified in box2d coords
targetY : table.y2box2d(y) // specified in box2d coords
};
this.joint = table.createMouseJoint(table.ground, this.paddle, mouseJointDef, true);
createPrismaticJoint
bodyA
bodyB
anchorX
anchorY
axisX
axisY
referenceAngle
jointDef
collideConnected
A prismatic joint allows for relative translation of two bodies along a specified axis.
Parameters:
-
bodyA
PhysicsBodyfirst connected body
-
bodyB
PhysicsBodysecond connected 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
Floatreference Angle
-
jointDef
ObjectOther 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
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// create the prismatic joint
// set joint
var jointDef = {
lowerTranslation : -3.0, // meters
upperTranslation : 5.0, // meters
enableLimit : true,
enableMotor : true,
motorSpeed : 1.0,
maxMotorForce : 100.0,
}
this._prismaticJoint = this.createPrismaticJoint(this._ground, this._rect1, System.width / 2, System.height / 2, 0.0, 1.0, 0.0, jointDef, true)
createPulleyJoint
bodyA
bodyB
groundAnchorAX
groundAnchorAY
groundAnchorBX
groundAnchorBY
anchorAX
anchorAY
anchorBX
anchorBY
ratio
collideConnected
The pulley joint is connection of two bodies and two fixed ground points. It looks like the body are connected with a rope, which comes throw the specified fixed ground points.
Parameters:
-
bodyA
PhysicsBodyfirst connected body
-
bodyB
PhysicsBodysecond connected 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
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// create the pulley joint
this._pulleyJoint = this.createPulleyJoint(this._rect1, this._rect2, System.width / 4, System.height / 8, 3 * System.width / 4, System.height / 8, System.width / 4, System.height / 2, 3 * System.width / 4, System.height / 2, 1.0 , true)
createRevoluteJoint
bodyA
bodyB
x
y
jointDef
collideConnected
The revolute joint can be thought of as a hinge, a pin, or an axle. Revolute joints can be given limits so that the bodies can rotate only to a certain point.
Parameters:
-
bodyA
PhysicsSpritefirst body in the joint
-
bodyB
PhysicsSpritesecond body in the joint
-
x
FloatX position of anchor point. Anchor point is point around which bodies are rotated.
-
y
FloatY position of anchor point. Anchor point is point around which bodies are rotated.
-
jointDef
Object{Object] Other 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 in radians per second. enableMotor- True / false to enable the joint motor
-
collideConnected
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// joint's options
var jointSet = {
enableMotor : true, // enable motor
motorSpeed : (- 2 * Math.PI / 3) * (800.0 / System.width), // final speed is linearly depends on radius (screen resolution)
maxMotorTorque : 2100000000, // maximum torque
}
// create joint
var joint = this.createRevoluteJoint(obj.bodyA, obj.bodyB, x, y, jointSet, true);
createWeldJoint
bodyA
bodyB
anchorX
anchorY
collideConnected
A weld joint essentially glues two bodies together. It may distort somewhat because the island constraint solver is approximate.
Parameters:
-
bodyA
PhysicsBodyfirst connected body
-
bodyB
PhysicsBodysecond connected body
-
anchorX
FloatX position of anchor point.
-
anchorY
FloatY position of anchor point.
-
collideConnected
BooleanIf this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.
Returns:
Example:
// create the weld joint
this._weldJoint = this.createWeldJoint(this._rect1, this._rect2, System.width / 2,System.height / 2, true)
destroyBody
body
Destroy body and remove it from bodies array. CAUTION: bodies should not be removed in the call back functions (onBeginContact or onEndContact). The better way is push all sprites to remove to an array and then remove it in onProcess event.
Parameters:
-
body
PhysicsBody
Example:
function process()
{
// remove sprites from the scene
for (var i in this._bodiesToDestory)
this.destroyBody(i);
}
destroyJoint
joint
Destroy existing joint. CAUTION: Joints should not be removed in the call back functions (like onBeginContact or onEndContact). The better way is push all joints to remove to an array and then remove it in onProcess event.
Parameters:
-
joint
B2JointJoint to destroy
Example:
function process()
{
// remove joints from the scene
for (var i in this._jointsToDestory)
this.destroyJoint(i);
}
doDebugDraw
Canvas
Draw physics scene, in debug mode
Parameters:
-
Canvas
Objectcanvas
draw
canvas
Draw physics scene. This function draws all sprites included in the scene. The function is called automatically as a reaction onto onDraw event. To customize scene appearance can be this function extended, but it can is neede to call also parent's draw method to ensure correct drawing of all objects in the scene.
Parameters:
-
canvas
CanvasCurrent scene canvas
Example:
function draw(canvas)
{
// draw background
canvas.drawRect(0, 0, System.width, System.height, this._bg);
// draw all other elements in the scene
super.draw(canvas);
}
endContact
PhysicsContact
endContact function is called as a reaction on the onEndContact event. This event is called when contact ends.
Parameters:
-
PhysicsContact
ObjectList of all contacts which appeared in last time step.
Example:
function endContact(contact)
{
// get the first contact
var current = contact;
while (current) {
// get the bodies in the contact
var bodyA = current.getBodyA();
var bodyB = current.getBodyB();
...
// get the next contact (they can be more contacts during the one step)
current = current.getNext();
}
}
getBody
body
Get body from bodies array.
Parameters:
-
body
B2Body
Returns:
getContactCount
() Integer
Get the number of contacts (each may have 0 or more contact points).
Returns:
getGravity
() Multivalue
Get the global gravity. The gravity affects all dynamic bodies (sprites) in the scene.
Returns:
Example:
var (gx, gy) = scene.getGravity();
init
()
Initialize basic properties, like debugDraw
setContinuousPhysics
Boolean
Enable/disable continuous physics. 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:
-
Boolean
Objectflag
setGravity
gx
gy
Set the global gravity. The gravity affects all dynamic bodies (sprites) in the scene.
Example:
scene.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
BooleanTure / false to enable / disable warm starting
step
[timeStep=1.0/40.0]
[velocityIterations=4]
[positionIterations=8]
Take a time step. This performs collision detection, integration, and constraint solution. This functin is usually called from process method every about 25 miliseconds.
Parameters:
Example:
function process()
{
// call parents process method
super.process();
// do physics math
this.step(1.0 / 40.0, 4, 8);
// redraw window
game.invalidate();
}
Properties
autoClearForces
Boolean
Flag to control automatic clearing of forces after each time step. By default it is set to true.
native
B2World
An instance of native b2World class used in physics scene for physical simulation. The value of this property is same as a value of PhysicsScene/world. This property is get only. To set the native world use PhysicsScene/world.
scale
Float
The width of the ohysics 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;
}
world
B2World
An instance of native b2World class used in physics scene for physical simulation. This property can be used to manually set world, if PhysicsScene is not created by create method.
Example:
// create an instance of b2World class manually in init function of extended class
class GameScene : PhysicsScene
{
function init()
{
super.init();
// create physics world
this.world = new b2World(0.0, -9.8, true, false);
...
}
...
}
// then instance of GameScene can be creates simply by key word new
var scene = new GameScene();
Events
onBeginContact
Event to be called, when two bodies collide.
Example:
this.onBeginContact = function(contact)
{
// get the first contact
var current = contact;
while (current) {
// get the bodies in the contact
var bodyA = current.getBodyA();
var bodyB = current.getBodyB();
...
// get the next contact (they can be more contacts during the one step)
current = current.getNext();
}
}
onEndContact
Event to be called, when contact ends.
Example:
this.onEndContact = function(contact)
{
// get the first contact
var current = contact;
while (current) {
// get the bodies in the contact
var bodyA = current.getBodyA();
var bodyB = current.getBodyB();
...
// get the next contact (they can be more contacts during the one step)
current = current.getNext();
}
}