Physics

Reference ❯ Dynamic Motion with Forces, Joints and Collisions

Creating Bodies

physics.body top ↑

Syntax

myBody = physics.body( CIRCLE, radius )

myBody = physics.body( POLYGON,
                       vec2(-10,10),
                       vec2(-10,-10),
                       vec2(10,-10),
                       vec2(10,10) )
                                                                  
myBody = physics.body( CHAIN, loop,
                       vec2(0,0),
                       vec2(10,5),
                       vec2(15,10) )
                       
myBody = physics.body( EDGE, vec2(0,0),
                             vec2(10,10) )

This type represents a dynamic rigid body.

type

int, the type of the body, can be STATIC, DYNAMIC or KINEMATIC

shapeType

readonly, the shape type of the body, can be CIRCLE, POLYGON, CHAIN or EDGE

radius

float, the radius of the body, only valid for circle shape types

points

table, a table containing the points that make up the body, only valid for polygon shape types

x

float, the x position of the body in pixels

y

float, the y position of the body in pixels

position

vec2, the position of the body

angle

float, the angle of the body in degrees

worldCenter

vec2, the center of mass of the body in world space

localCenter

vec2, the center of mass of the body in local space

linearVelocity

vec2, the current linear velocity of the body in pixels per second

angularVelocity

float, the angular velocity of the body in degrees per second

density

float, the density of the body in kg/m^2, 1 by default, cannot be negative

mass

float, the mass of the body in kg, cannot be negative. If you set this, density will be ignored

inertia

float, the moment of inertia of the body. Cannot be set

restitution

float, the restitution, or 'bouncyness' of the body

friction

float, the friction of the body determines how easy the object slides. This defaults to 0.2.

categories

table, an array of the categories (1 to 16) to which the body belongs to for collision filtering. The default is {1}.

mask

table, an array of the categories of bodies with which the body will collide. The default is all categories, {1, 2, ..., 15, 16}.

fixedRotation

boolean, locks the rotation of this body

active

boolean, set to false to remove from simulation

sensor

boolean, whether the body is a sensor. Collision information is generated for sensors, but they do not physically affect the scene.

awake

boolean, true if body is currently awake, false otherwise

sleepingAllowed

boolean, set to false to prevent bodies from sleeping (default: true)

bullet

boolean, set to true for fast moving bodies to prevent tunneling

gravityScale

float, controls the influence of gravity on this body, 1 by default

linearDamping

float, the amount of linear damping applied to this body. Damping reduces the world velocity of bodies, and is different from friction in that it occurs regardless of contact.

angularDamping

float, the amount of angular damping applied to this body.

interpolate

boolean, controls render interpolation, used to smooth out motion but introduces slight lag

joints

table, returns the list of joints connected to this body

info

value, used for storing arbitrary data in this body

Examples

-- create a circle with 25px radius circle = physics.body(CIRCLE, 25)

CIRCLE top ↑

Syntax

CIRCLE

This constant specifies the circle shape type.Circle shapes are the fastest and simplest of the shape types, defined with a single parameter, radius.

Returns

int

POLYGON top ↑

Syntax

POLYGON

This constant specifies the polygon shape type.Polygon shapes are defined by a series of vertices. Non convex polygons are automatically decomposed into a set of convex polygons.

Returns

int

CHAIN top ↑

Syntax

CHAIN

This constant specifies the chain shape type.Chain shapes are defined by a series of vertices that form an equivalent set of connected edges. This shape type has no mass and cannot be used in dynamic bodies.

Returns

int

EDGE top ↑

Syntax

EDGE

This constant specifies the edge shape type.Edge shapes are defined by two vertices, which form a straight line. This shape type has no mass and cannot be used in dynamic bodies.

Returns

int

DYNAMIC top ↑

Syntax

DYNAMIC

This constant specifies the dynamic body type.Dynamic bodies move under the influence of collisions, forces, joints and gravity.

Returns

int

STATIC top ↑

Syntax

STATIC

This constant specifies the static body type.Static bodies are unaffected by forces and collisions. They also do not collide with other static or kinematic bodies.Also note that you cannot attach two static/kinematic bodies together with a joint.

Returns

int

KINEMATIC top ↑

Syntax

KINEMATIC

This constant specifies the kinematic body type.Kinematic bodies are unaffected by forces and collisions. Unlike static bodies, kinematic bodies are meant to be moved, usually by setting linear velocity directly. They also do not collide with other static or kinematic bodies.Also note that you cannot attach two static/kinematic bodies together with a joint.

Returns

int

body.applyForce( force ) top ↑

Syntax

myBody:applyForce( force )
myBody:applyForce( force, worldPoint )

Applies a force to this body object. If worldPoint is not specified then the force will be applied to the center of the body.

force

vec2, the amount of force to apply as a vector

worldPoint

vec2, the point to apply the force from, in world coordinates

body.applyTorque( torque ) top ↑

Syntax

myBody:applyTorque( applyTorque )

Applies torque to this body object.

torque

float, the amount of torque

body.applyLinearImpulse( impulse ) top ↑

Syntax

myBody:applyLinearImpulse( impulse )
myBody:applyLinearImpulse( impulse, worldPoint )

Applies a linear impulse to this body object. If worldPoint is not specified then the impulse will apply to the center of the body.

impulse

vec2, the impulse to apply as a vector

worldPoint

vec2, the point to apply the impulse from, in world coordinates

body.applyAngularImpulse( impulse ) top ↑

Syntax

myBody:applyAngularImpulse( impulse )

Applies an angular impulse to this body object.

impulse

float, the angular impulse

body.destroy() top ↑

Syntax

myBody:destroy()

A body will be removed from the simulation automatically when garbage collected, however this may not happen immediately. To ensure that a body is removed from the simulation, use destroy(). Please note that all methods and properties will cease to work after destroy() is called.

Examples

-- destroy should be used before -- setting a body to nil circle = physics.body(CIRCLE, 100) circle:destroy() circle = nil

body.testPoint( worldPoint ) top ↑

Syntax

myBody:testPoint( worldPoint )

Tests if worldPoint is inside this body.

worldPoint

vec2, the point to test for intersection, in world space

Examples

-- test if CurrentTouch is inside this body circle = physics.body(CIRCLE, 100) point = vec2(CurrentTouch.x, CurrentTouch.y) if circle:testPoint(point) then print("HIT!") end

Returns

true if worldPoint is inside this body, false otherwise

body.testOverlap( otherBody ) top ↑

Syntax

myBody:testOverlap( otherBody )

Tests if this body intersects with otherBody.This is useful if you want to do simple shape intersection tests that do not require realtime contact information.

otherBody

body, the body to test for intersection with

Examples

-- test if two bodies overlap circle1 = physics.body(CIRCLE, 100) circle2 = physics.body(CIRCLE, 10) if circle1:testOverlap(circle2) then print("HIT!") end

Returns

true if this body is intersecting with otherBody, false otherwise

body.getLocalPoint( worldPoint ) top ↑

Syntax

myBody:getLocalPoint( worldPoint )

Converts a point to the local coordinate space of this body

Returns

vec2, coordinate in local space of this body

body.getWorldPoint( localPoint ) top ↑

Syntax

myBody:getWorldPoint( localPoint )

Converts a point from the local coordinate space of this body to world space

Returns

vec2, coordinate in world space

body.getLinearVelocityFromWorldPoint( point ) top ↑

Syntax

myBody:getLinearVelocityFromWorldPoint( worldPoint )

Samples the linear velocity of this body at a given point in world space.

Returns

vec2, linear velocity at worldPoint of this body

body.getLinearVelocityFromLocalPoint( point ) top ↑

Syntax

myBody:getLinearVelocityFromLocalPoint( worldPoint )

Samples the linear velocity of this body at a given point in local space.

Returns

vec2, linear velocity at localPoint of this body

Handling Contacts Between Bodies

Contacts Overview top ↑

A contact occurs whenever two bodies collide with each other. Codea allows you to handle contacts by implementing a global function called collide( contact ) in your code.

-- This gets called whenever two bodies collide
function collide( contact )
    if contact.state == BEGAN then
        print("HIT!")
    end
end

Contact objects contain information about the collision, such as the state, position of the collision, which bodies were involved, and so on. For a full listing of data available in a contact, see the physics.contact documentation.

physics.contact top ↑

This type represents a collision between two bodies.

A physics.contact object is supplied to the global function collide( contact ) whenever a two bodies collide, maintain contact over multiple frames, or separate from each other. The contact supplied by this event will remain static as it is only a copy of the underlying physical state.

id

number, a unique id that represents this contact

state

int, the current state of this contact, can be BEGAN, CHANGED, ENDED

touching

bool, whether or not the contact is currently touching. Due to the way contacts are cached this can be false under some circumstances.

position

vec2, the current position of this contact

normal

vec2, the current normal of this contact

normalImpulse

float, the magnitude of energy used to separate the two colliding bodies projected along the normal vector. Useful for measuring the strength of an impact

tangentImpulse

float, the magnitude of energy used to separate the two colliding bodies projected along the tangent vector (perpendicular to the normal). Useful for measuring the friction of an impact

pointCount

int, the number of points in the contact manifold

points

table, an array of vec2's describing the contact manifold

bodyA

body, the first body in the collision represented by this contact

bodyB

body, the second body in the collision represented by this contact

Examples

function collide(contact) if contact.state == BEGAN then print("HIT!") end end

Attaching Bodies with Joints

physics.joint top ↑

Syntax

physics.joint( REVOLUTE, bodyA, bodyB, 
                         anchor )

physics.joint( PRISMATIC, bodyA, bodyB,
                          anchorA, 
                          direction )

physics.joint( DISTANCE, bodyA, bodyB,
                         anchorA, 
                         anchorB )

physics.joint( WELD, bodyA, bodyB, 
                            anchor )
                            
physics.joint( ROPE, bodyA, bodyB,
                         anchorA, 
                         anchorB,
                         maxLength )
                            

This type represents a joint that constrains two rigid bodies together.

type

int, the type of the joint, can be REVOLUTE, DISTANCE, PRISMATIC, WELD or ROPE

bodyA

body, the first body attached to this joint

bodyB

body, the second body attached to this joint

anchorA

vec2, the anchor for the first body in world coordinates

anchorB

vec2, the anchor for the second body in world coordinates

reactionForce

vec2, the current amount of force used by the joint to constrain the relative motion between the two bodies. This can be used to break joints when the force reaches a given threshold

reactionTorque

float, the current amount of torque used by the joint to constrain the relative rotation between the two bodies. This can be used to break joints when the torque reaches a given threshold

enableLimit

boolean, whether or not the limit for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have limits

lowerLimit

float, the lower limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit

upperLimit

float, the upper limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit

enableMotor

boolean, whether or not the motor for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have motors

motorSpeed

float, the desired speed of the motor. For REVOLUTE joints this is in degrees per second. For PRISMATIC joints this is specified in pixels per second

maxMotorTorque

float, the maximum amount of torque the motor can apply to reach the desired motor speed. Only REVOLUTE joints have this property

maxMotorForce

float, the maximum amount of force the motor can apply to reach the desired motor speed. Only PRISMATIC joints have this property

length

float, the length of the joint. Only applies to DISTANCE joints

frequency

float, The softness of the joint, set to zero for stiff joints. Only applies to DISTANCE and WELD joints

dampingRatio

float, Controls the damping of soft joints, higher values reduce oscillation, set to zero for stiff joints. Only applies to DISTANCE and WELD joints

maxLength

float, Controls the maximum length (distance between anchor points) of the joint. Only applies to ROPE joints

REVOLUTE top ↑

Syntax

REVOLUTE

This constant specifies the revolute joint type. Revolute joints constrain two bodies so that they rotate about a single anchor point.

Returns

int

DISTANCE top ↑

Syntax

DISTANCE

This constant specifies the distance joint type. Distance joints constrain two bodies so that they maintain a fixed distance between their respective anchor points. The length of a distance joint is taken from the initial distance between the two anchor points in world space. Setting the frequency and damping ratio of the joint allows for soft spring-like behaviour.

Returns

int

PRISMATIC top ↑

Syntax

PRISMATIC

This constant specifies the prismatic joint type. Prismatic joints constrain the motion of two bodies along the axis between the two specified anchor points. This allows for telescopic motion, while restricting relative rotation between the two bodies.

Returns

int

WELD top ↑

Syntax

WELD

This constant specifies the weld joint type. Weld joints constrain the motion and relative rotation between two bodies, effectively turning them into a single body. Due to the iterative nature of the solver, weld joints can bend when put under stress and may fail completely when large forces are involved or several weld joints are chained together to form a larger object.

Returns

int

ROPE top ↑

Syntax

ROPE

This constant specifies the rope joint type. Rope joints constrain the maximum distance between two bodies.

Returns

int

Physics Simulation Functions

physics.pause() top ↑

Syntax

-- pause physics
physics.pause()

Pauses the physics simulation.

physics.resume() top ↑

Syntax

-- resume physics
physics.resume()

Resumes the physics simulation.

physics.raycast( start, end, ... ) top ↑

Syntax

physics.raycast(start, end)
physics.raycast(start, end, category1)
physics.raycast(start, end, category1, 
                            category2)

Performs a raycast from the start point to the end point.Any additional parameters are treated as category filters, allowing certain bodies to be ignored. This function only returns hit information on the closest rigid body detected.

start

vec2, the start point of the ray (technically a line segment, but finite for practical purposes)

end

vec2, the end point of the ray

Returns

table, if the raycast intersects a body this function will return a table containing the following key-value pairs:

body => detected 
point => point of intersection
normal => normal on surface of hit body
fraction => fraction of total ray length from start to intersecton point

physics.raycastAll( start, end, ... ) top ↑

Syntax

physics.raycastAll(start, end)
physics.raycastAll(start, end, category1)
physics.raycastAll(start, end, category1, 
                               category2)

Performs a raycast from the start point to the end point.Any additional parameters are treated as category filters, allowing certain bodies to be ignored. This function returns an array of tables describing all objects hit along the ray, ordered from closest to farthest.

start

vec2, the start point of the ray (technically a line segment, but finite for practical purposes)

end

vec2, the end point of the ray

Returns

array, if the raycast intersects one or more bodies this function will an array of tables containing the following key-value pairs

body => detected body
point => point of intersection
normal => normal on surface of hit body
fraction => fraction of total ray length from start to intersecton point

physics.queryAABB( lowerLeft, upperRight, ... ) top ↑

Syntax

physics.queryAABB(lowerLeft, upperRight)

physics.queryAABB(lowerLeft, upperRight, 
                  category1)

physics.queryAABB(lowerLeft, upperRight,
                  category1, category2)

Performs a query to find all bodies within the supplied axis-aligned bounding box.Any additional parameters are treated as category filters, allowing certain bodies to be ignored.

lowerLeft

vec2, the position of the lower left corner of the query axis-aligned bounding box

upperRight

vec2, the position of the upper right corner of the query axis-aligned bounding box

Returns

array, returns all bodies that lie within the supplied bounding box

physics.gravity( x, y ) top ↑

Syntax

physics.gravity()
physics.gravity( x, y )
physics.gravity( grav )
physics.gravity( Gravity )

Sets the gravity of the world, units are in pixels per second^2. Use the Gravity global to set to device gravity. When no parameters are passed, function returns current world gravity as a vec2.

x

float, gravity in the x-axis

y

float, gravity in the y-axis

grav

vec2, gravity in both axes

Gravity

vec3, device gravity used as a special case

Returns

vec2, the current world gravity if no parameters are supplied

physics.iterations( velIterations, posIterations ) top ↑

Syntax

physics.iterations( velocityIterations,
                    positionIterations )

Sets the iterations used by the physics solver. Larger iterations tend to result in more stable physics, but will slow down the simulation.

velocityIterations

int, the number of velocity iterations performed each time step (default: 10)

positionIterations

int, the number of position iterations performed each time step (default: 8)

physics.pixelToMeterRatio top ↑

Syntax

ratio = physics.pixelToMeterRatio
physics.pixelToMeterRatio = ratio

Sets the ratio between pixels and meters in the simulation.This is used to make objects on the screen appear at a reasonable scale, while allowing the physics engine to remain stable. The default value is 32, meaning that for every 32 pixels in screen space there is 1 meter in physics space. This can be largely ignored in most cases, however if dealing with objects much larger or smaller than the default settings, it can be useful to change the ratio to something closer to that scale.

Returns

int, the current ratio

physics.continous top ↑

Syntax

physics.continuous = true

Sets whether the physics engine performs continuous collision detection. Continuous collision detection ensures that very fast moving bodies do not pass through thin objects.

You must also set the bullet property to true on any physics body you wish to use with continuous collision detection.

By default, this value is false because continuous physics increases the computational cost of running the physics engine.

Returns

bool, whether continous collision is set