2D Rigid-Body Physics Engine (`engine.Physics`)

A built-in 2D rigid-body simulation supporting gravity vectors, linear velocities, restitution, dynamic bodies, static terrain colliders, and AABB/circle collision detection.

Functions & Methods Reference

Function / Method Signature Description
engine.Physics.createWorld(gx, gy) (num, num) → World Initializes a new physics simulation world with gravity vector (gx, gy).
world:addBody(type, x, y) (int, num, num) → Body Spawns a rigid body. type = 1 for dynamic (moving) bodies, type = 0 for static immovable obstacles.
world:step(dt) (num) → void Simulates physics forward by dt seconds. Automatically handled when passed to engine.run().
body:setRect(w, h) (num, num) → void Attaches an axis-aligned bounding box collider of width w and height h.
body:setCircle(radius) (num) → void Attaches a circular collider with given radius.
body:setVelocity(vx, vy) (num, num) → void Assigns linear velocity in pixels per second.
body:getVelocity() () → (num, num) Returns the current velocity vx, vy.
body:getPosition() () → (num, num) Returns the current simulation position x, y.
body:setPosition(x, y) (num, num) → void Teleports the body to (x, y) coordinates.

Bouncing Ball Simulation Example

physics_bounce.lua
import engine

win = engine.Window.create("Physics Demo", 800, 600)
world = engine.Physics.createWorld(0, 500) -- Gravity downward: 500 px/s²

-- Create a dynamic falling ball:
ball = world:addBody(1, 400, 50)
ball:setCircle(20)
ball:setVelocity(50, 0)

-- Create a static floor collider:
floor = world:addBody(0, 400, 550)
floor:setRect(750, 40)

engine.run({
    window = win,
    physicsWorld = world,
    draw = function() {
        engine.Graphics.clear(0.1, 0.1, 0.15, 1.0)

        -- Draw ball at current physical coordinates:
        bx, by = ball:getPosition()
        engine.Graphics.drawCircle(bx, by, 20, 1.0, 0.3, 0.3, 1.0)

        -- Draw floor:
        fx, fy = floor:getPosition()
        engine.Graphics.drawRect(fx - 375, fy - 20, 750, 40, 0.3, 0.8, 0.4, 1.0)
    }
})