# Physics 2D

Dynamic motion with forces, joints and collisions in 2D

[Reference](index.md)

<a id="section-Guides"></a>

## Guides

<a id="2D-Physics-in-Codea"></a>

### 2D Physics in Codea

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()`:

```lua
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:

```lua
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:

```lua
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:

```lua
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:

```lua
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](data/downloads/A-standalone-physics-world-57e8ec798abd.zip) — Open in Codea to run this example.

```lua
-- 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](data/downloads/Combining-bodies-joints-and-scene-callbacks-4377dda82135.zip) — Open in Codea to run this example.

```lua
-- 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**

```lua
-- #######
-- 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

```

<a id="section-Simulation"></a>

## Simulation

<a id="physics2d.world"></a>

### world

```lua
world
```

create a new 2D physics world

<a id="world"></a>

### world()

```lua
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

create a new 2D physics world

#### Returns

- **physics2d.world**: 

#### A standalone physics world

[Download project](data/downloads/A-standalone-physics-world-57e8ec798abd.zip) — Open in Codea to run this example.

```lua
-- 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

```

<a id="world:body"></a>

### world:body(type, x, y)

```lua
world:body(type, x, y)
```

Create a new rigidbody in this world

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

<a id="world:step"></a>

### world:step(deltaTime)

```lua
world:step(deltaTime)
```

Steps the simulation by `deltaTime`

step the physics simulation

#### Parameters

- **deltaTime** (number, optional): Simulation timestep, in seconds.

<a id="world:draw"></a>

### world:draw()

```lua
world:draw()
```

Draws a debug representation of the physics world using primitive shapes

draw a debug representation of the physics world

<a id="world:raycast"></a>

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

```lua
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

perform a raycast in this physics world

#### 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

<a id="world:overlapBox"></a>

### world:overlapBox(origin, size, mask)

```lua
world:overlapBox(origin, size, mask)
```

check if a box overlaps any collider

#### 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.

<a id="world:queryBox"></a>

### world:queryBox(origin, size, mask)

```lua
world:queryBox(origin, size, mask)
```

query colliders overlapping a box

#### 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.

<a id="world:queryBoxAll"></a>

### world:queryBoxAll(origin, size, mask)

```lua
world:queryBoxAll(origin, size, mask)
```

query all colliders overlapping a box

#### 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.

<a id="world.gravity"></a>

### world.gravity

```lua
world.gravity
```

The current gravity vector for this world

get or set the 2D physics gravity vector

<a id="physics2d.body"></a>

### body

```lua
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…)

destroy this body

<a id="body:destroy"></a>

### body:destroy()

```lua
body:destroy()
```

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

destroy this body

<a id="body:circle"></a>

### body:circle(radius, offsetX, offsetY)

```lua
body:circle(radius, offsetX, offsetY)
```

Creates and attaches a circle collider to this body

attach 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

<a id="body:box"></a>

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

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

Creates and attaches a box collider to this body

attach 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

<a id="body:polygon"></a>

### body:polygon(points)

```lua
body:polygon(points)
```

Creates and attaches a polygon collider to this body

attach 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

<a id="body:hinge"></a>

### body:hinge(anchor)

```lua
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

attach a hinge joint to this body

#### Parameters

- **anchor** (vec2): The world-space anchor for one or two-body hinges

#### Returns

- **physics2d.hinge**: The new hinge joint

<a id="body:slider"></a>

### body:slider(anchor, axis)

```lua
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

attach a slider joint to this body

#### 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

<a id="body:distance"></a>

### body:distance(anchorA, anchorB)

```lua
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

attach a distance joint to this body

#### 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

<a id="body:applyForce"></a>

### body:applyForce(force)

```lua
body:applyForce(force)
```

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

apply a continuous force to this body

#### Parameters

- **force** (vec2): The force vector to apply

<a id="body:applyTorque"></a>

### body:applyTorque(torque)

```lua
body:applyTorque(torque)
```

apply a torque to this body

#### Parameters

- **torque** (number): The torque vector to apply

<a id="body:applyLinearImpulse"></a>

### body:applyLinearImpulse(impulse)

```lua
body:applyLinearImpulse(impulse)
```

apply a linear impulse to this body

#### Parameters

- **impulse** (vec2): The linear impulse to apply

<a id="body:applyAngularImpulse"></a>

### body:applyAngularImpulse(impulse)

```lua
body:applyAngularImpulse(impulse)
```

apply an angular impulse to this body

#### Parameters

- **impulse** (number): The angular impulse to apply

<a id="body:worldPoint"></a>

### body:worldPoint(localPoint)

```lua
body:worldPoint(localPoint)
```

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

transform a local point to world space

#### Parameters

- **localPoint** (vec2): The local space point to transform

#### Returns

- **vec2**: 

<a id="body:worldVector"></a>

### body:worldVector(localVector)

```lua
body:worldVector(localVector)
```

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

transform a local vector to world space

#### Parameters

- **localVector** (vec2): The world space vector to transform

#### Returns

- **vec2**: 

<a id="body:localPoint"></a>

### body:localPoint(worldPoint)

```lua
body:localPoint(worldPoint)
```

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

transform a world point to local space

#### Parameters

- **worldPoint** (vec2): The world space point to transform

#### Returns

- **vec2**: 

<a id="body:localVector"></a>

### body:localVector(worldVector)

```lua
body:localVector(worldVector)
```

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

transform a world vector to local space

#### Parameters

- **worldVector** (vec2): The world space vector to transform

#### Returns

- **vec2**: 

<a id="body:velocityAtLocalPoint"></a>

### body:velocityAtLocalPoint(localPoint)

```lua
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

sample the body velocity at a local point

#### Parameters

- **localPoint** (vec2): The local point to sample velocity from

#### Returns

- **vec2**: 

<a id="body:velocityAtWorldPoint"></a>

### body:velocityAtWorldPoint(worldPoint)

```lua
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

sample the body velocity at a world point

#### Parameters

- **worldPoint** (vec2): The world point to sample velocity from

#### Returns

- **vec2**: 

<a id="body.destroyed"></a>

### body.destroyed

```lua
body.destroyed
```

Flag indicating that this body has already been destroyed

get whether this body or collider is destroyed

<a id="body.position"></a>

### body.position

```lua
body.position
```

The position of this body in the simulated world

get or set the position of this body

<a id="body.mass"></a>

### body.mass

```lua
body.mass
```

The mass of this body in kilograms

get the mass of this body

<a id="body.inertia"></a>

### body.inertia

```lua
body.inertia
```

The interial tensor in kg m^2

get or set the inertia of this body

<a id="body.linearVelocity"></a>

### body.linearVelocity

```lua
body.linearVelocity
```

The linear velocity of the body

get or set the linear velocity

<a id="body.angularVelocity"></a>

### body.angularVelocity

```lua
body.angularVelocity
```

The angular velocity of the body

get or set the angular velocity

<a id="body.linearDamping"></a>

### body.linearDamping

```lua
body.linearDamping
```

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

get or set the linear damping

<a id="body.angularDamping"></a>

### body.angularDamping

```lua
body.angularDamping
```

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

get or set the angular damping

<a id="body.gravityScale"></a>

### body.gravityScale

```lua
body.gravityScale
```

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

get or set the gravity scale

<a id="body.bullet"></a>

### body.bullet

```lua
body.bullet
```

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

get or set whether bullet mode is enabled

<a id="body.sleepingAllowed"></a>

### body.sleepingAllowed

```lua
body.sleepingAllowed
```

Flag for allowing sleeping for this body

get or set whether sleeping is allowed

<a id="body.awake"></a>

### body.awake

```lua
body.awake
```

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

get or set whether this body is awake

<a id="body.enabled"></a>

### body.enabled

```lua
body.enabled
```

Flag for whether simulation is enabled

get or set whether this body or joint is enabled

<a id="body.fixedRotation"></a>

### body.fixedRotation

```lua
body.fixedRotation
```

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

get or set whether rotation is fixed

<a id="body.onCollisionBegan"></a>

### body.onCollisionBegan

```lua
body.onCollisionBegan
```

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

callback invoked when collision begins

<a id="body.onCollisionEnded"></a>

### body.onCollisionEnded

```lua
body.onCollisionEnded
```

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

callback invoked when collision ends

<a id="body.onPreSolve"></a>

### body.onPreSolve

```lua
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](https://box2d.org/documentation/classb2_contact_listener.html)

callback invoked before collision is resolved

<a id="body.onPostSolve"></a>

### body.onPostSolve

```lua
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](https://box2d.org/documentation/classb2_contact_listener.html)

callback invoked after collision is resolved

<a id="section-Collision"></a>

## Collision

<a id="physics2d.collider"></a>

### collider

```lua
collider
```

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

destroy this collider

<a id="collider:destroy"></a>

### collider:destroy()

```lua
collider:destroy()
```

Destroys this collider, removing it in the next simluation step

destroy this collider

<a id="collider.destroyed"></a>

### collider.destroyed

```lua
collider.destroyed
```

Flag indicating that this collider has already been destroyed

get whether this body or collider is destroyed

<a id="collider.friction"></a>

### collider.friction

```lua
collider.friction
```

The coefficient of friction for this collider

get or set the friction coefficient

<a id="collider.density"></a>

### collider.density

```lua
collider.density
```

The density of this collider

get or set the density

<a id="collider.restitution"></a>

### collider.restitution

```lua
collider.restitution
```

The coefficient of restitution for this collider

get or set the restitution coefficient

<a id="collider.sensor"></a>

### collider.sensor

```lua
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

get or set whether this collider is a sensor

<a id="collider.category"></a>

### collider.category

```lua
collider.category
```

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

get or set the collision category bitfield

#### Example

```lua
PLAYER_CAT = 0x1 -- set bit 1
ENEMY_CAT = 0x2 -- set bit 2
ITEM_CAT = 0x4 -- 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
```

<a id="collider.mask"></a>

### collider.mask

```lua
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

get or set the collision mask bitfield

<a id="collider.group"></a>

### collider.group

```lua
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

get or set the collision group

<a id="collider.body"></a>

### collider.body

```lua
collider.body
```

The body this collider belongs to

get the body this collider belongs to

<a id="physics2d.circle"></a>

### circle

```lua
circle
```

get or set the radius

<a id="circle.radius"></a>

### circle.radius

```lua
circle.radius
```

get or set the radius

<a id="circle.center"></a>

### circle.center

```lua
circle.center
```

get or set the center point

<a id="physics2d.box"></a>

### box

```lua
box
```

get or set the center point

<a id="box.center"></a>

### box.center

```lua
box.center
```

get or set the center point

<a id="box.size"></a>

### box.size

```lua
box.size
```

get or set the size

<a id="box.angle"></a>

### box.angle

```lua
box.angle
```

get or set the angle

<a id="physics2d.polygon"></a>

### polygon

```lua
polygon
```

get or set the polygon points

<a id="polygon.points"></a>

### polygon.points

```lua
polygon.points
```

get or set the polygon points

<a id="physics2d.contact"></a>

### contact

```lua
contact
```

Represents physical contact between two colliders during a collision

get or set whether this body or joint is enabled

<a id="contact.enabled"></a>

### contact.enabled

```lua
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)

get or set whether this body or joint is enabled

<a id="contact.touching"></a>

### contact.touching

```lua
contact.touching
```

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

get whether these bodies are touching

<a id="contact.friction"></a>

### contact.friction

```lua
contact.friction
```

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

get or set the friction coefficient

<a id="contact.restitution"></a>

### contact.restitution

```lua
contact.restitution
```

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

get or set the restitution coefficient

<a id="contact.tangentSpeed"></a>

### contact.tangentSpeed

```lua
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

get or set the tangent speed

<a id="contact.localPoint"></a>

### contact.localPoint

```lua
contact.localPoint
```

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

get the local contact point

<a id="contact.worldPoint"></a>

### contact.worldPoint

```lua
contact.worldPoint
```

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

get the world contact point

<a id="contact.localNormal"></a>

### contact.localNormal

```lua
contact.localNormal
```

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

get the local contact normal

<a id="contact.worldNormal"></a>

### contact.worldNormal

```lua
contact.worldNormal
```

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

get the world contact normal

<a id="contact.body"></a>

### contact.body

```lua
contact.body
```

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

get the body this collider belongs to

<a id="contact.otherBody"></a>

### contact.otherBody

```lua
contact.otherBody
```

The second body involved in this collision contact

get the other body in the contact

<a id="contact.collider"></a>

### contact.collider

```lua
contact.collider
```

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

get the collider in the contact

<a id="contact.otherCollider"></a>

### contact.otherCollider

```lua
contact.otherCollider
```

The second collider involved in this collision contact

get the other collider in the contact

<a id="physics2d.rayHit"></a>

### rayHit

```lua
rayHit
```

get the contact or raycast hit point

<a id="rayHit.point"></a>

### rayHit.point

```lua
rayHit.point
```

The world position of the raycast hit location

get the contact or raycast hit point

<a id="rayHit.normal"></a>

### rayHit.normal

```lua
rayHit.normal
```

The world normal of the raycast hit location

get the contact or raycast hit normal

<a id="rayHit.fraction"></a>

### rayHit.fraction

```lua
rayHit.fraction
```

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

get the raycast hit fraction

<a id="rayHit.collider"></a>

### rayHit.collider

```lua
rayHit.collider
```

The collider that was hit by the ray

get the collider in the contact

<a id="rayHit.body"></a>

### rayHit.body

```lua
rayHit.body
```

The body of the collider that was hit by the ray

get the body this collider belongs to

<a id="section-Constraints"></a>

## Constraints

<a id="physics2d.joint"></a>

### joint

```lua
joint
```

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

destroy this joint

<a id="joint:destroy"></a>

### joint:destroy()

```lua
joint:destroy()
```

Destroys this joint, removing it in the next simluation step

destroy this joint

<a id="joint:getReactionForce"></a>

### joint:getReactionForce(invDt)

```lua
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

get the reaction force applied to this joint

#### Parameters

- **invDt** (number): The inverse timestep

<a id="joint:getReactionTorque"></a>

### joint:getReactionTorque(invDt)

```lua
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

get the reaction torque applied to this joint

#### Parameters

- **invDt** (number): The inverse timestep

<a id="joint.enabled"></a>

### joint.enabled

```lua
joint.enabled
```

Enable/disable this joint

get or set whether this joint is enabled

<a id="joint.destroyed"></a>

### joint.destroyed

```lua
joint.destroyed
```

Flag set to true if this joint has already been destroyed

get whether this joint is destroyed

<a id="joint.collideConnected"></a>

### joint.collideConnected

```lua
joint.collideConnected
```

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

get or set whether connected bodies collide

<a id="joint.anchorA"></a>

### joint.anchorA

```lua
joint.anchorA
```

The anchor point for the first body in world space

get or set anchor point A in world space

<a id="joint.anchorB"></a>

### joint.anchorB

```lua
joint.anchorB
```

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

get or set anchor point B in world space

<a id="joint.localAnchorA"></a>

### joint.localAnchorA

```lua
joint.localAnchorA
```

The anchor point for the first body in local space

get or set local anchor point A

<a id="joint.localAnchorB"></a>

### joint.localAnchorB

```lua
joint.localAnchorB
```

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

get or set local anchor point B

<a id="joint.other"></a>

### joint.other

```lua
joint.other
```

The other physics body attached to this joint

get the other body connected by this joint

<a id="physics2d.hinge"></a>

### hinge

```lua
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

get or set the reference angle

<a id="hinge.referenceAngle"></a>

### hinge.referenceAngle

```lua
hinge.referenceAngle
```

The initial relative angle of the two connected bodies

get or set the reference angle

<a id="hinge.angle"></a>

### hinge.angle

```lua
hinge.angle
```

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

get or set the angle

<a id="hinge.speed"></a>

### hinge.speed

```lua
hinge.speed
```

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

get or set the motor speed

<a id="hinge.useMotor"></a>

### hinge.useMotor

```lua
hinge.useMotor
```

Enable/disables the joint motor (off by default)

get or set whether the motor is enabled

<a id="hinge.maxTorque"></a>

### hinge.maxTorque

```lua
hinge.maxTorque
```

The maximum amount of torque to apply use the motor

get or set the maximum motor torque

<a id="hinge.motorSpeed"></a>

### hinge.motorSpeed

```lua
hinge.motorSpeed
```

The target speed of the motor

get or set the motor speed

<a id="hinge.useLimit"></a>

### hinge.useLimit

```lua
hinge.useLimit
```

Enables/disables angular joint limits (off by default)

get or set whether limits are enabled

<a id="hinge.lowerLimit"></a>

### hinge.lowerLimit

```lua
hinge.lowerLimit
```

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

get or set the lower joint limit

<a id="hinge.upperLimit"></a>

### hinge.upperLimit

```lua
hinge.upperLimit
```

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

get or set the upper joint limit

<a id="physics2d.slider"></a>

### slider

```lua
slider
```

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

get or set the reference angle

<a id="slider.referenceAngle"></a>

### slider.referenceAngle

```lua
slider.referenceAngle
```

The initial relative angle of the two connected bodies

get or set the reference angle

<a id="slider.translation"></a>

### slider.translation

```lua
slider.translation
```

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

get the joint translation

<a id="slider.speed"></a>

### slider.speed

```lua
slider.speed
```

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

get or set the motor speed

<a id="slider.useMotor"></a>

### slider.useMotor

```lua
slider.useMotor
```

Enable/disables the joint motor (off by default)

get or set whether the motor is enabled

<a id="slider.maxForce"></a>

### slider.maxForce

```lua
slider.maxForce
```

The maximum amount of force to apply use the motor

get or set the maximum motor force

<a id="slider.motorSpeed"></a>

### slider.motorSpeed

```lua
slider.motorSpeed
```

The target speed of the motor

get or set the motor speed

<a id="slider.useLimit"></a>

### slider.useLimit

```lua
slider.useLimit
```

Enables/disables linear joint limits (off by default)

get or set whether limits are enabled

<a id="slider.lowerLimit"></a>

### slider.lowerLimit

```lua
slider.lowerLimit
```

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

get or set the lower joint limit

<a id="slider.upperLimit"></a>

### slider.upperLimit

```lua
slider.upperLimit
```

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

get or set the upper joint limit

<a id="physics2d.distance"></a>

### distance

```lua
distance
```

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

get or set the rope length

<a id="distance.length"></a>

### distance.length

```lua
distance.length
```

get or set the rope length

<a id="distance.currentLength"></a>

### distance.currentLength

```lua
distance.currentLength
```

get the current rope length

<a id="distance.stiffness"></a>

### distance.stiffness

```lua
distance.stiffness
```

get or set the spring stiffness

<a id="distance.damping"></a>

### distance.damping

```lua
distance.damping
```

get or set the spring damping

<a id="distance.minLength"></a>

### distance.minLength

```lua
distance.minLength
```

get or set the minimum rope length

<a id="distance.maxLength"></a>

### distance.maxLength

```lua
distance.maxLength
```

get or set the maximum rope length

<a id="physics2d.pulley"></a>

### pulley

```lua
pulley
```

*Not implemented yet*

<a id="physics2d.target"></a>

### target

```lua
target
```

*Not implemented yet*

<a id="physics2d.gear"></a>

### gear

```lua
gear
```

*Not implemented yet*

<a id="physics2d.weld"></a>

### weld

```lua
weld
```

*Not implemented yet*

<a id="physics2d.friction"></a>

### friction

```lua
friction
```

*Not implemented yet*

<a id="physics2d.rope"></a>

### rope

```lua
rope
```

*Not implemented yet*

<a id="physics2d.motor"></a>

### motor

```lua
motor
```

*Not implemented yet*
