Codea icon Physics 2D

Reference › Dynamic motion with forces, joints and collisions in 2D

Guides

2D Physics in Codea top ↑

Overview

Use 2D physics to make objects fall, bounce, collide, and swing from joints. Codea uses Box2D to simulate their motion.

Add physics bodies to a scene for automatic simulation, or create a physics2d.world and advance it yourself.

Creating Physics Worlds

Create a world, add bodies, and advance it with world:step():

function setup()
    world = physics2d.world()
    world.gravity = vec2(0, -9.8)

    -- Static ground
    ground = world:body(physics2d.STATIC)
    ground:add(physics2d.box(WIDTH, 20))
    ground.position = vec2(WIDTH/2, 10)

    -- Dynamic circle
    ball = world:body(physics2d.DYNAMIC)
    ball:add(physics2d.circle(20))
    ball.position = vec2(WIDTH/2, HEIGHT/2)
end

function update(dt)
    world:update(dt)
end

function draw()
    background(40, 40, 50)
    fill(255, 100, 100)
    circle(ball.position.x, ball.position.y, 20)
end

Body types:

  • physics2d.STATIC — immovable, acts as ground or walls
  • physics2d.DYNAMIC — moved by forces and gravity
  • physics2d.KINEMATIC — moved manually, pushes dynamic bodies

Using Physics with Entities

Attach 2D physics components to scene entities for automatic simulation:

function setup()
    scn = scene()

    -- Set up a 2D canvas camera
    local cam = scn:entity("camera")
    cam:add(camera.rigs.canvas)

    -- Ground
    local ground = scn:entity("ground")
    ground:add(physics2d.body(physics2d.STATIC))
    ground:add(physics2d.box(400, 20))
    ground.position = vec3(WIDTH/2, 10, 0)

    -- Ball
    local ball = scn:entity("ball")
    ball.sprite = asset.builtin.Blocks.Yellow_Circle
    ball:add(physics2d.body(physics2d.DYNAMIC))
    ball:add(physics2d.circle(32))
    ball.position = vec3(WIDTH/2, HEIGHT/2, 0)

    scene.main = scn
end

Collision Shapes

  • physics2d.circle(radius) — circular collider
  • physics2d.box(width, height) — rectangular collider
  • physics2d.polygon(vertices) — arbitrary convex polygon, vertices as a table of vec2
  • physics2d.chain(vertices, loop) — open or closed chain of line segments (STATIC only)
  • physics2d.edge(start, end) — single line segment (STATIC only)

Collision Callbacks

React to collisions through entity callbacks:

local ball = scn:entity()
ball:add(physics2d.body(physics2d.DYNAMIC))
ball:add(physics2d.circle(20))

ball.collisionBegan2d = function(contact)
    print("Collision with impulse:", contact.normalImpulse)
end

Sensors

Sensors detect when objects overlap without pushing them apart. Use them for pickup areas or goal zones:

local trigger = scn:entity("trigger")
trigger:add(physics2d.body(physics2d.STATIC))
local col = trigger:add(physics2d.circle(50))
col.isSensor = true

trigger.collisionBegan2d = function(contact)
    print("Something entered the trigger zone")
end

Forces and Impulses

Control dynamic bodies with forces and impulses:

local body = ent:get(physics2d.body)

-- Push upward continuously (apply in update)
body:applyForce(vec2(0, 500))

-- Instant kick
body:applyImpulse(vec2(100, 0))

-- Set velocity directly
body.linearVelocity = vec2(5, 0)

Stepping a physics world yourself

Tap to drop boxes onto a floor. fixedUpdate(dt) advances the simulation, and screenToWorld() converts each tap to a position in the world. world:draw() shows the collision shapes; replace it with your own drawing for a game.

Stepping a physics world yourself

Download project Open in Codea to run this example.

Show code (56 lines)
-- Physics in Codea

function setup()
    -- Create a 2D physics world
    world = physics2d.world()

    -- Once you have a physics world you can start creating bodies, which represent our simulated objects
    -- We can create 3 types of bodies:
    -- static - an immovable object that stays in one place
    -- dynamic - a dynamic object that moves and responds to gravity and collisions
    -- kinematic - like a static object but it can also move, hitting other objects

    -- Create a static floor for things to fall on and set position to 0, -5
    floor = world:body(STATIC, 0, -5)
    -- The box method attaches a box collider to our floor body (5 meters by 0.5 meters)
    floor:box(20, 0.5)

    -- Create a dynamic box to fall on our floor
    body = world:body(DYNAMIC, 0, 0)
    body:box(1, 1)

    body2 = world:body(DYNAMIC, 0, 3)
    body2:circle(0.5)

    -- Create a 2D camera to scale the world (our physics world uses meters as units, rather than pixels)
    cam = camera.ortho(10, 0, 100) -- make the screen 20 units wide
end

-- The fixedUpdate function gets called a fixed number of times every second
-- This is useful for physics simulations, keeping them stable
function fixedUpdate(dt)
    world:step(dt) -- advance the physics simulation by one frame
end

function draw()
    background(25, 25, 25)

    -- Use our camera to scale the screen to the right units
    cam:apply()
    -- Draw the physics world (you can use your own shapes but this is just handy to get started quickly)
    world:draw()
end

function touched(touch)
    -- We can also use our camera to convert touches from the screen to our physics units
    -- Using that we can spawn more physics shapes after each touch
    if touch.state == BEGAN then
        cam:apply() -- Apply the camera so we can convert to/from the physics units
        -- Convert from touch coordinates to world coordinates
        local x, y = cam:screenToWorld(touch.x, touch.y)
        -- Make a body at this x,y position
        local body = world:body(DYNAMIC, x, y)
        body:box(1, 1)
    end
end

Combining bodies, joints, and scene callbacks

Touch either side to move the character’s hinged legs, or drag a body to pull it. Collisions change its expression and play a sound. scene.main advances the simulation automatically; you do not need to call world:step().

Combining bodies, joints, and scene callbacks

Download project Open in Codea to run this example.

Show code (156 lines)
-- 2D Physics in Scenes
--
-- Adding a body to a scene entity will automatically enable
-- physics for it. You can use callbacks to tap into various
-- physics features, including hit tests (for touches) and
-- collisions (to react to physical events)

-- Create and attach an eyeball to something
function eye(x, y, parent)
    local eye = scn:entity()
    eye.parent = parent
    eye.x = x
    eye.y = y
    local c = eye:add(physics2d.body, DYNAMIC):circle(0.25)
    c.sensor = true

    -- Draw an eye shape on top of this rigidbody
    function eye:draw()
        matrix.reset().translate(self.position)
        style.push().sortOrder(-3) -- use sortOrder to draw in-front
        fill(255)
        ellipse(0, 0, 0.6)
        fill(0)
        ellipse(0, 0, 0.45)
        fill(255)
        matrix.push().scale(math.sin(time.elapsed * 30) * 0.15 + 1.0)
        ellipse(-.1, .1, .3)
        ellipse(.1, .1, .08)
        ellipse(.1, -.1, .1)
        matrix.pop()
        style.pop()
    end

    local p = eye.worldPosition
    local j = eye.body2d:distance(parent.body2d, p.x, p.y, p.x, p.y + 0.1)
    j.minLength = 0
    j.maxLength = 0.125
end

-- Create and attach a leg to something
function leg(name, x, y, parent)
    local leg = scn:entity(name)
    leg.parent = parent

    function leg:draw()
        style.push().sortOrder(-1).rectMode(CENTER)
        style.stroke(255).strokeWidth(0.05).fill(221, 85, 142)
        rect(0, 0, 0.6, 0.8, 0.3)
        style.pop()
    end

    leg.x = x
    leg.y = y
    leg:add(physics2d.body, DYNAMIC):box(0.3, 0.6)
    local p = leg.worldPosition
    local j = leg.body2d:hinge(parent.body2d, p.x, p.y + 0.2)
    j.useMotor = true
    j.motorSpeed = 0
    j.maxTorque = 20

    function leg:update(dt)
        if touch.current.x < WIDTH/2 and touch.current.state ~= ENDED then
            j.motorSpeed = -5
        elseif touch.current.x > WIDTH/2 and touch.current.state ~= ENDED then
            j.motorSpeed = 5
        else
            j.motorSpeed = 0
        end
    end
end

function setup()
    -- Create a default 2d scene
    scn = scene.default2d()
    scn.physics2d.debugDraw = true

    cam = scn.camera:get(camera)
    cam.orthoSize = 8
    scn.camera.y = 2

    function scn.camera:update(dt)
        self.position = ball.position
    end

    scn.camera:add(physics2d.grabber)

    floor = scn:entity("floor")
    floor:add(physics2d.body, KINEMATIC):box(20, 0.5)

    -- New entity
    ball = scn:entity('ball')
    -- Add a physics body and attach a circle collider to it
    ball:add(physics2d.body, DYNAMIC):circle(1.0)
    ball.body2d.fixedRotation = true
    ball.y = 8
    -- Custom entity property
    ball.ouch = 0

    function ball:draw()
        style.push().sortOrder(-2) -- draw in front of physics objects
        style.stroke(255).strokeWidth(0.05).fill(221, 85, 142)
        ellipse(0, 0, 2.0)

        -- Draw a different expression if recently hit something
        if math.abs(time.elapsed - self.ouch) < 0.5 then
            -- :O
            style.noStroke().fill(0)
            ellipse(0, -0.2, 0.2)
        else
            -- :)
            style.noFill().stroke(0).strokeWidth(0.1)
            line(-0.1, -0.1, 0.1, -0.1)
        end

        style.pop()
    end

    -- Respond to collision events
    function ball:collisionBegan2d(hit)
        -- Play a sound and record when the hit happened
        if math.abs(time.elapsed - self.ouch) > 0.5 then
            sound.play(SOUND_HURT, math.random(0, 10000))
        end

        self.ouch = time.elapsed
    end

    -- Attach all the body parts
    eye(-0.5, 0, ball)
    eye(0.5, 0, ball)
    leg("leftLeg", -0.8, -0.8, ball)
    leg("rightLeg", 0.8, -0.8, ball)

    -- Create a concave 2D polygon (which is automatically decomposed into convex shapes)
    local points =
    {
        vec2(-1, 1),
        vec2(-0.8, 1),
        vec2(-0.5, 0.0),
        vec2(0.5, 0.0),
        vec2(0.8, 1),
        vec2(1, 1),
        vec2(1, -1),
        vec2(-1, -1),
    }
    poly = scn:entity()
    poly.rz = 180
    poly:add(physics2d.body, DYNAMIC):polygon(points)
    poly.y = 3

    scene.main = scn
end

function draw()
end

Grabber.lua — querying bodies and applying a spring-like force

Show code (64 lines)
-- #######
-- Grabber
-- #######
-- Add's a touch-based grabber to interact with physics objects
-- Simply add to your scene camera:
--     scn.camera:add(physics2d.grabber)

local grabber = class('grabber')

function grabber:created()
    self.world = self.scene.world2d
    -- Need the camera for translating touches to world space
    self.cam = self.entity:get(camera)
end

function grabber:touched(touch)
    -- Convert touches from screen to world space using the camera
    local wx, wy = self.cam:screenToWorld(touch.x, touch.y)
    local point = vec2(wx, wy)

    if touch.began then
        -- Check for a hit when touches began
        local hit = self.world:queryBox(point, 0, 0)
        -- Ensure the found body is dynamic
        if hit and hit.body.type == DYNAMIC then
            -- Keep track of it and the local point that was grabbed
            self.body = hit.body
            self.anchor = self.body:localPoint(point)
            return true
        end
    elseif touch.moving then
        self.target = point
    elseif touch.ended then
        self.anchor = nil
        self.target = nil
        self.body = nil
    end
end

-- Visualise the grabber force / anchor point
function grabber:draw()
    if self.anchor and self.target then
        matrix.push().reset()
        style.push().noFill().stroke(255).strokeWidth(0.1).sortOrder(-10)
        local wp = self.body:worldPoint(self.anchor)
        line(wp, self.target)
        style.noStroke().fill(255)
        ellipse(wp, 0.2)
        ellipse(self.target, 0.2)
        style.pop()
        matrix.pop()
    end
end

function grabber:fixedUpdate(dt)
    if self.anchor and self.target then
        local wp = self.body:worldPoint(self.anchor)
        local v = self.target - wp
        self.body:applyForce(v * 100 - self.body:velocityAtWorldPoint(wp) * 10.0, wp)
    end
end

physics2d.grabber = grabber

Simulation

world top ↑

Type

Syntax

world

world()

Constructor

Syntax

world()

A standalone world must be advanced explicitly in fixedUpdate(dt). This example adds a static floor, dynamic bodies, and touch-to-world conversion for spawning more boxes.

Create a new physics world

Returns

physics2d.world

A standalone physics world

Download project Open in Codea to run this example.

Show code (56 lines)
-- Physics in Codea

function setup()
    -- Create a 2D physics world
    world = physics2d.world()

    -- Once you have a physics world you can start creating bodies, which represent our simulated objects
    -- We can create 3 types of bodies:
    -- static - an immovable object that stays in one place
    -- dynamic - a dynamic object that moves and responds to gravity and collisions
    -- kinematic - like a static object but it can also move, hitting other objects

    -- Create a static floor for things to fall on and set position to 0, -5
    floor = world:body(STATIC, 0, -5)
    -- The box method attaches a box collider to our floor body (5 meters by 0.5 meters)
    floor:box(20, 0.5)

    -- Create a dynamic box to fall on our floor
    body = world:body(DYNAMIC, 0, 0)
    body:box(1, 1)

    body2 = world:body(DYNAMIC, 0, 3)
    body2:circle(0.5)

    -- Create a 2D camera to scale the world (our physics world uses meters as units, rather than pixels)
    cam = camera.ortho(10, 0, 100) -- make the screen 20 units wide
end

-- The fixedUpdate function gets called a fixed number of times every second
-- This is useful for physics simulations, keeping them stable
function fixedUpdate(dt)
    world:step(dt) -- advance the physics simulation by one frame
end

function draw()
    background(25, 25, 25)

    -- Use our camera to scale the screen to the right units
    cam:apply()
    -- Draw the physics world (you can use your own shapes but this is just handy to get started quickly)
    world:draw()
end

function touched(touch)
    -- We can also use our camera to convert touches from the screen to our physics units
    -- Using that we can spawn more physics shapes after each touch
    if touch.state == BEGAN then
        cam:apply() -- Apply the camera so we can convert to/from the physics units
        -- Convert from touch coordinates to world coordinates
        local x, y = cam:screenToWorld(touch.x, touch.y)
        -- Make a body at this x,y position
        local body = world:body(DYNAMIC, x, y)
        body:box(1, 1)
    end
end

world:body(type, x, y)

Method

Syntax

world:body(type, x, y)

Create a new rigidbody in this world

Parameters

type enum.

The type of body, STATIC, DYNAMIC or KINEMATIC

x number.

The initial x position of the new body

y number.

The initial y position of the new body

world:step(deltaTime)

Method

Syntax

world:step(deltaTime)

Steps the simulation by deltaTime

Parameters

deltaTime number, optional.

Simulation timestep, in seconds.

world:draw()

Method

Syntax

world:draw()

Draws a debug representation of the physics world using primitive shapes

world:raycast(origin, direction, distance, mask)

Method

Syntax

world:raycast(origin, direction, distance, mask)

Performs a raycast on the physics world from origin in the direction of direction for the distance of distance

The raycast itself is filtered by the optional mask parameter, a bitfield which is compared to collider categories

Parameters

origin vec2.

The origin of the ray

direction vec2.

The direction of the ray

distance number.

The maximum distance for the ray to travel

mask integer, optional.

Collision category bit mask restricting which bodies can be hit.

Returns

physics2d.rayHit

The raycast hit info or nil is no collider was hit

world:overlapBox(origin, size, mask)

Method

Syntax

world:overlapBox(origin, size, mask)

Parameters

origin vec2.

Anchor or query position in world space; see the overload description for local joint anchors.

size vec2.

Dimensions of the query box.

mask integer, optional.

Collision category bit mask restricting which bodies can be hit.

world:queryBox(origin, size, mask)

Method

Syntax

world:queryBox(origin, size, mask)

Parameters

origin vec2.

Anchor or query position in world space; see the overload description for local joint anchors.

size vec2.

Dimensions of the query box.

mask integer, optional.

Collision category bit mask restricting which bodies can be hit.

world:queryBoxAll(origin, size, mask)

Method

Syntax

world:queryBoxAll(origin, size, mask)

Parameters

origin vec2.

Anchor or query position in world space; see the overload description for local joint anchors.

size vec2.

Dimensions of the query box.

mask integer, optional.

Collision category bit mask restricting which bodies can be hit.

world.gravity

Property

Syntax

world.gravity

The current gravity vector for this world

body top ↑

Type

Syntax

body

A two dimensional rigidbody that simulated within a physics2d.world. Used to simulate both dynamic and static objects, responding to physical forces, collisions and physics queries (i.e. raycast, queryBox, etc…)

body:destroy()

Method

Syntax

body:destroy()

Destroys this body, removing it from the world in the next simluation step

body:circle(radius, offsetX, offsetY)

Method

Syntax

body:circle(radius, offsetX, offsetY)

Creates and attaches a circle collider to this body

Parameters

radius number.

The radius of the circle

offsetX number, optional.

The local x offset of the circle

offsetY number, optional.

The local y offset of the circle

Returns

physics2d.circle

The new circle collider

body:box(halfWidth, halfHeight, offsetX, offsetY, rotation)

Method

Syntax

body:box(halfWidth, halfHeight, offsetX, offsetY, rotation)

Creates and attaches a box collider to this body

Parameters

halfWidth number.

Half the extent of the box along the corresponding axis.

halfHeight number.

Half the extent of the box along the corresponding axis.

offsetX number, optional.

Local offset of the shape along the corresponding axis.

offsetY number, optional.

Local offset of the shape along the corresponding axis.

rotation number, optional.

Local rotation of the shape in degrees.

Returns

physics2d.box

The new box collider

body:polygon(points)

Method

Syntax

body:polygon(points)

Creates and attaches a polygon collider to this body

Parameters

points table.

Array of vertices defining a convex polygon in body-local coordinates.

Returns

physics2d.polygon

The new polygon collider

body:hinge(anchor)

Method

Syntax

body:hinge(anchor)

Creates and attaches a hinge joint to this body. When no other body is provided the hinge joint attaches to the world itself

For two-body joints when one anchor is provided, it will be interpreted as a world space location, which will attach to the relative locations of both bodies. When two anchors (anchorA and anchorB) are provided, they will be interpreted in local space and attach to those locations directly

Parameters

anchor vec2.

The world-space anchor for one or two-body hinges

Returns

physics2d.hinge

The new hinge joint

body:slider(anchor, axis)

Method

Syntax

body:slider(anchor, axis)

Creates and attaches a slider joint to this body. When no other body is provided the slider joint attaches to the world itself

Parameters

anchor vec2.

Anchor or query position in world space; see the overload description for local joint anchors.

axis vec2.

Direction of the joint axis.

Returns

physics2d.slider

The new slider joint

body:distance(anchorA, anchorB)

Method

Syntax

body:distance(anchorA, anchorB)

Creates and attaches a distance joint to this body. When no other body is provided the distance joint attaches to the world itself.

For two-body joints when one anchor is provided, it will be interpreted as a world space location, which will attach to the relative locations of both bodies. When two anchors are provided, they will be interpreted in local space and attach to those locations directly

Parameters

anchorA vec2.

Anchor or query position in world space; see the overload description for local joint anchors.

anchorB vec2.

Anchor or query position in world space; see the overload description for local joint anchors.

Returns

physics2d.distance

The new distance joint

body:applyForce(force)

Method

Syntax

body:applyForce(force)

Applies a force to this body over time (non-instantanious). Ideal for physical effects such as wind, bouyancy and springs

Parameters

force vec2.

The force vector to apply

body:applyTorque(torque)

Method

Syntax

body:applyTorque(torque)

Parameters

torque number.

The torque vector to apply

body:applyLinearImpulse(impulse)

Method

Syntax

body:applyLinearImpulse(impulse)

Parameters

impulse vec2.

The linear impulse to apply

body:applyAngularImpulse(impulse)

Method

Syntax

body:applyAngularImpulse(impulse)

Parameters

impulse number.

The angular impulse to apply

body:worldPoint(localPoint)

Method

Syntax

body:worldPoint(localPoint)

Transforms localPoint from local space to world space in respect to this body

Parameters

localPoint vec2.

The local space point to transform

Returns

vec2

body:worldVector(localVector)

Method

Syntax

body:worldVector(localVector)

Transforms localVector from world space to local space in respect to this body

Parameters

localVector vec2.

The world space vector to transform

Returns

vec2

body:localPoint(worldPoint)

Method

Syntax

body:localPoint(worldPoint)

Transforms worldPoint from world space to local space in respect to this body

Parameters

worldPoint vec2.

The world space point to transform

Returns

vec2

body:localVector(worldVector)

Method

Syntax

body:localVector(worldVector)

Transforms worldVector from world space to local space in respect to this body

Parameters

worldVector vec2.

The world space vector to transform

Returns

vec2

body:velocityAtLocalPoint(localPoint)

Method

Syntax

body:velocityAtLocalPoint(localPoint)

Samples the velocity of the body at localPoint in local space

Useful for determining velocity on a body at a specific location for calculating effects, sounds and damage during collisions

Parameters

localPoint vec2.

The local point to sample velocity from

Returns

vec2

body:velocityAtWorldPoint(worldPoint)

Method

Syntax

body:velocityAtWorldPoint(worldPoint)

Samples the velocity of the body at worldPoint in world space

Useful for determining velocity on a body at a specific location for calculating effects, sounds and damage during collisions

Parameters

worldPoint vec2.

The world point to sample velocity from

Returns

vec2

body.destroyed

Property

Syntax

body.destroyed

Flag indicating that this body has already been destroyed

body.position

Property

Syntax

body.position

The position of this body in the simulated world

body.mass

Property

Syntax

body.mass

The mass of this body in kilograms

body.inertia

Property

Syntax

body.inertia

The interial tensor in kg m^2

body.linearVelocity

Property

Syntax

body.linearVelocity

The linear velocity of the body

body.angularVelocity

Property

Syntax

body.angularVelocity

The angular velocity of the body

body.linearDamping

Property

Syntax

body.linearDamping

The amount of linear damping to apply, slowing velocity proportionally over time

body.angularDamping

Property

Syntax

body.angularDamping

The amount of linear damping to apply, slowing rotation propotionally over time

body.gravityScale

Property

Syntax

body.gravityScale

The scale factor to apply to global gravity, settings 0 will disable gravity

body.bullet

Property

Syntax

body.bullet

Continuous physics switch for this body, used to prevent tunneling for fast moving objects

body.sleepingAllowed

Property

Syntax

body.sleepingAllowed

Flag for allowing sleeping for this body

body.awake

Property

Syntax

body.awake

Flag for the current awake state of this body, set to true to wake immediately

body.enabled

Property

Syntax

body.enabled

Flag for whether simulation is enabled

body.fixedRotation

Property

Syntax

body.fixedRotation

Flag for fixed rotation state, set to false to disable rotation

body.onCollisionBegan

Property

Syntax

body.onCollisionBegan

A callback for when a collision with this body begins, with more information provided by the supplied physics2d.contact object

body.onCollisionEnded

Property

Syntax

body.onCollisionEnded

A callback for when a collision with this body ends, with more information provided by the supplied physics2d.contact object

body.onPreSolve

Property

Syntax

body.onPreSolve

A callback for when a collision with this body is about to be solved, allowing for some physics2d.contact parameters to be modified

See: https://box2d.org/documentation/classb2_contact_listener.html

body.onPostSolve

Property

Syntax

body.onPostSolve

A callback for when a collision with this body has been solved, allowing for some physics2d.contact information to be used for other purposes

See: https://box2d.org/documentation/classb2_contact_listener.html

Collision

collider top ↑

Type

Syntax

collider

A two dimensional collider that attaches to a physics2d.body, detects and reacts to collisions

collider:destroy()

Method

Syntax

collider:destroy()

Destroys this collider, removing it in the next simluation step

collider.destroyed

Property

Syntax

collider.destroyed

Flag indicating that this collider has already been destroyed

collider.friction

Property

Syntax

collider.friction

The coefficient of friction for this collider

collider.density

Property

Syntax

collider.density

The density of this collider

collider.restitution

Property

Syntax

collider.restitution

The coefficient of restitution for this collider

collider.sensor

Property

Syntax

collider.sensor

Flag turning this collider into a sensor. Sensors do not physically collide with object bodies but will still report collision detection via callbacks

collider.category

Property

Syntax

collider.category

The category for this collider. Categories are used to filter collisions based on their mask bits

Example

PLAYER_CAT =  -- set bit 1
ENEMY_CAT =  -- set bit 2
ITEM_CAT =  -- set bit 3

-- Players can collider with enemies and items
playerCollider.category = PLAYER_CAT
playerCollider.mask = ENEMY_CAT | ITEM_CAT

-- Enemies only collider with players
enemyCollider.category = ENEMY_CAT
enemyCollider.mask = PLAYER_CAT

-- Items only collider with players
itemCollider.category = ITEM_CAT
itemCollider.mask = PLAYER_CAT

collider.mask

Property

Syntax

collider.mask

The mask determines what categories this collider will pass collision filtering. If the mask bits are set for at least one category of a potential collision partner then a collision will be possible

collider.group

Property

Syntax

collider.group

The group index is used for another extra layer of collision filtering. If two colliders have the same group and are positive, they will always collide, and if they are both negative then they will never collide

collider.body

Property

Syntax

collider.body

The body this collider belongs to

circle top ↑

Type

Syntax

circle

circle.radius

Property

Syntax

circle.radius

circle.center

Property

Syntax

circle.center

box top ↑

Type

Syntax

box

box.center

Property

Syntax

box.center

box.size

Property

Syntax

box.size

box.angle

Property

Syntax

box.angle

polygon top ↑

Type

Syntax

polygon

polygon.points

Property

Syntax

polygon.points

contact top ↑

Type

Syntax

contact

Represents physical contact between two colliders during a collision

contact.enabled

Property

Syntax

contact.enabled

Whether the contact is currently enabled, which can be set to false within the physics2d.body.onPreSolve callback

Useful for one way platforms (checking collision normals and conditionally disabling them)

contact.touching

Property

Syntax

contact.touching

Where the contact is currently touching (in some cases this may be false during collision resolution substeps)

contact.friction

Property

Syntax

contact.friction

The friction of this contact, which can be modified within the physics2d.body.onPreSolve callback

contact.restitution

Property

Syntax

contact.restitution

The restitution of this contact, which can be modified within the physics2d.body.onPreSolve callback

contact.tangentSpeed

Property

Syntax

contact.tangentSpeed

The tangent of this contact, which can be modified within the physics2d.body.onPreSolve callback

Useful for creating things like conveyor belts which have a moving surface while remaining stationary

contact.localPoint

Property

Syntax

contact.localPoint

The local position of the contact point (averaged from the manifold)

contact.worldPoint

Property

Syntax

contact.worldPoint

The world position of the contact point (averaged from the manifold)

contact.localNormal

Property

Syntax

contact.localNormal

The local normal of the contact point (averaged from the manifold)

contact.worldNormal

Property

Syntax

contact.worldNormal

The world normal of the contact point (averaged from the manifold)

contact.body

Property

Syntax

contact.body

The first body in this contact (the body receiving the callback)

contact.otherBody

Property

Syntax

contact.otherBody

The second body involved in this collision contact

contact.collider

Property

Syntax

contact.collider

The first collider in this contact (attached to the body recieving the callback)

contact.otherCollider

Property

Syntax

contact.otherCollider

The second collider involved in this collision contact

rayHit top ↑

Type

Syntax

rayHit

rayHit.point

Property

Syntax

rayHit.point

The world position of the raycast hit location

rayHit.normal

Property

Syntax

rayHit.normal

The world normal of the raycast hit location

rayHit.fraction

Property

Syntax

rayHit.fraction

The fraction of the total ray distance travelled before a hit was detected

rayHit.collider

Property

Syntax

rayHit.collider

The collider that was hit by the ray

rayHit.body

Property

Syntax

rayHit.body

The body of the collider that was hit by the ray

Constraints

joint top ↑

Type

Syntax

joint

The base class of physical constraints between two bodies (i.e. joints)

joint:destroy()

Method

Syntax

joint:destroy()

Destroys this joint, removing it in the next simluation step

joint:getReactionForce(invDt)

Method

Syntax

joint:getReactionForce(invDt)

Gets the reaction force applied to this joint in the previous frame to keep the constraint satisfied

Call with 1/physicsTimestep to get accurate results

Parameters

invDt number.

The inverse timestep

joint:getReactionTorque(invDt)

Method

Syntax

joint:getReactionTorque(invDt)

Gets the reaction torque applied to this joint in the previous frame to keep the constraint satisfied

Call with 1/physicsTimestep to get accurate results

Parameters

invDt number.

The inverse timestep

joint.enabled

Property

Syntax

joint.enabled

Enable/disable this joint

joint.destroyed

Property

Syntax

joint.destroyed

Flag set to true if this joint has already been destroyed

joint.collideConnected

Property

Syntax

joint.collideConnected

When enabled bodies connected by a joint will collide with each other. Disabled by default

joint.anchorA

Property

Syntax

joint.anchorA

The anchor point for the first body in world space

joint.anchorB

Property

Syntax

joint.anchorB

The anchor point for the second (attached) body in world space

joint.localAnchorA

Property

Syntax

joint.localAnchorA

The anchor point for the first body in local space

joint.localAnchorB

Property

Syntax

joint.localAnchorB

The anchor point for the second (attached) body in local space

joint.other

Property

Syntax

joint.other

The other physics body attached to this joint

hinge top ↑

Type

Syntax

hinge

A hinge type joint, pinning the bodies together at the respective anchor points, while allowing for free rotation with optional motor and angular limits

hinge.referenceAngle

Property

Syntax

hinge.referenceAngle

The initial relative angle of the two connected bodies

hinge.angle

Property

Syntax

hinge.angle

The current angle (in degrees) between the two connected bodies relative to the reference angle

hinge.speed

Property

Syntax

hinge.speed

The current angular speed of the joint (in degrees per second)

hinge.useMotor

Property

Syntax

hinge.useMotor

Enable/disables the joint motor (off by default)

hinge.maxTorque

Property

Syntax

hinge.maxTorque

The maximum amount of torque to apply use the motor

hinge.motorSpeed

Property

Syntax

hinge.motorSpeed

The target speed of the motor

hinge.useLimit

Property

Syntax

hinge.useLimit

Enables/disables angular joint limits (off by default)

hinge.lowerLimit

Property

Syntax

hinge.lowerLimit

The lower angular rotation limit in degrees (when limits are enabled)

hinge.upperLimit

Property

Syntax

hinge.upperLimit

The upper angular rotation limit in degrees (when limits are enabled)

slider top ↑

Type

Syntax

slider

A sliding (prismatic) joint allowing for translation along a single axis

slider.referenceAngle

Property

Syntax

slider.referenceAngle

The initial relative angle of the two connected bodies

slider.translation

Property

Syntax

slider.translation

The current relative translation between the two bodies along the constained axis

slider.speed

Property

Syntax

slider.speed

The current relative speed between the two bodies along the constrained axis

slider.useMotor

Property

Syntax

slider.useMotor

Enable/disables the joint motor (off by default)

slider.maxForce

Property

Syntax

slider.maxForce

The maximum amount of force to apply use the motor

slider.motorSpeed

Property

Syntax

slider.motorSpeed

The target speed of the motor

slider.useLimit

Property

Syntax

slider.useLimit

Enables/disables linear joint limits (off by default)

slider.lowerLimit

Property

Syntax

slider.lowerLimit

The lower linear translation limit in meters (when limits are enabled)

slider.upperLimit

Property

Syntax

slider.upperLimit

The upper linear translation limit in meters (when limits are enabled)

distance top ↑

Type

Syntax

distance

A distance based joint constraint with spring-like properties and distance based limits

distance.length

Property

Syntax

distance.length

distance.currentLength

Property

Syntax

distance.currentLength

distance.stiffness

Property

Syntax

distance.stiffness

distance.damping

Property

Syntax

distance.damping

distance.minLength

Property

Syntax

distance.minLength

distance.maxLength

Property

Syntax

distance.maxLength

pulley top ↑

Type

Syntax

pulley

Not implemented yet

target top ↑

Type

Syntax

target

Not implemented yet

gear top ↑

Type

Syntax

gear

Not implemented yet

weld top ↑

Type

Syntax

weld

Not implemented yet

friction top ↑

Type

Syntax

friction

Not implemented yet

rope top ↑

Type

Syntax

rope

Not implemented yet

motor top ↑

Type

Syntax

motor

Not implemented yet