DatumHueEnterprise v0.0.24datumhue.com
Contents

12345678Build a ball pit · Step 4 of 8

Add physics

You'll learn15 min
  • Add static and dynamic bodies
  • Make bodies bounce
  • Push bodies with impulses
  • Leave dynamic bodies to the simulation
Time
15 min
Builds on
Step 3: Make it interactive
File
pit.lua

So far your own code has moved every ball. In this step you hand that job to physics: the balls fall, bounce off the walls and knock into each other, and a Shake button throws them back up.

Let the balls fall

Physics works on the shapes you already draw. DrawPrimitive:add_body gives a shape a body, and from then on physics decides how it moves. This step uses two kinds of body:

  • A static body never moves. Walls and floors are static.
  • A dynamic body falls, bounces and collides. The simulation moves it, not your code.

Replace pit.lua with this version. It drops the movement code from step 3, and adds gravity and four walls:

pit.lualua+27 new, 22 removed
local color = datumhue.color
local theme = datumhue.theme
local vec2 = datumhue.math.vec2

local W, H, R = 480, 320, 12
local COLORS = { "#e67e80", "#dbbc7f", "#7fbbb3" }

New line: datumhue.physics.gravity = vec2(0, -600)
New line: 
local screen = datumhue.ui.root:panel({
    width = "100%",
    height = "100%",
    flex_direction = "column",
    justify_content = "center",
    align_items = "center",
    gap = 12,
})

local toolbar = screen:panel({
    flex_direction = "row",
    align_items = "center",
    gap = 8,
})
local add = toolbar:button({ text = "Add ball" })
local clear = toolbar:button({ text = "Clear" })
local count = toolbar:label({
    text = "Balls: 0",
    color = theme.token("accent_primary"),
})

local canvas = datumhue.draw.new({
    width = W,
    height = H,
    background = color("#232a2e"),
})
canvas:mount({ parent = screen, width = W, height = H })

New line: local function wall(x, y, width, height)
New line:     local rect = canvas:rect({
New line:         pos = vec2(x, y),
New line:         width = width,
New line:         height = height,
New line:         color = color("#475258"),
New line:     })
New line:     rect:add_body({ type = "static" })
New line: end
New line: 
New line: wall(-W / 2, -H / 2, W, 10) -- floor
New line: wall(-W / 2, H / 2 - 10, W, 10) -- ceiling
New line: wall(-W / 2, -H / 2, 10, H) -- left
New line: wall(W / 2 - 10, -H / 2, 10, H) -- right
New line: 
local balls = {}

local function add_ball()
New line:     local x = math.random(-200, 200)
New line:     local y = math.random(0, 120)
New line:     local ball = canvas:circle({
New line:         pos = vec2(x, y),
        radius = R,
        color = color(COLORS[#balls % #COLORS + 1]),
    })
New line:     ball:add_body({
New line:         type = "dynamic",
New line:         shape = "circle",
New line:         restitution = 0.7,
    })
New line:     table.insert(balls, ball)
    count.text = "Balls: " .. #balls
end

local function clear_balls()
    for _, ball in ipairs(balls) do
New line:         ball:remove()
    end
    balls = {}
    count.text = "Balls: 0"
end

add:on_click(add_ball)
clear:on_click(clear_balls)

datumhue.input.on_key(function(key, pressed)
    if key == "a" and pressed then
        add_ball()
    end
end)

for _ = 1, 10 do
    add_ball()
end

In this example: datumhue.color datumhue.theme datumhue.math.vec2 datumhue.physics.gravity datumhue.ui.root UiElement:panel UiElement:button UiElement:label datumhue.theme.token datumhue.draw.new DrawCanvas:mount DrawCanvas:rect DrawPrimitive:add_body DrawCanvas:circle UiElement.text UiElement:on_click datumhue.input.on_key

  • datumhue.physics.gravity pulls on every body in your app. On a canvas it is in pixels: vec2(0, -600) speeds a falling ball up by 600 pixels per second, every second. The default pull is far too gentle for a canvas.
  • wall draws a rectangle and gives it a static body. DrawCanvas:rect places a rectangle by its bottom-left corner, where a circle goes by its center, so the four calls line the edges of the canvas.
  • Each ball gets a dynamic body with shape = "circle", sized from the drawing.
  • restitution is how bouncy a body is, from 0 (no bounce) to 1 (no speed lost). When two bodies hit, they bounce by the average of their two values. The walls keep the default, so a ball bounces a little less off a wall than off another ball.
  • The on_update function is gone, and so is each ball's table: the shape is the ball now, and the simulation moves it.

Shake the pit

To move a dynamic body, give it a kick. DrawPrimitive:apply_impulse works like a bat hitting a ball: the body's speed changes at once, by the impulse divided by the body's mass.

A ball's mass comes from its size, in the hundreds for these, so a kick of 400 would barely stir it. With mass = 1, an impulse is the change of speed itself, in pixels per second. Add a Shake button that kicks every ball:

pit.lualua+10 new lines
local color = datumhue.color
local theme = datumhue.theme
local vec2 = datumhue.math.vec2

local W, H, R = 480, 320, 12
local COLORS = { "#e67e80", "#dbbc7f", "#7fbbb3" }

datumhue.physics.gravity = vec2(0, -600)

local screen = datumhue.ui.root:panel({
    width = "100%",
    height = "100%",
    flex_direction = "column",
    justify_content = "center",
    align_items = "center",
    gap = 12,
})

local toolbar = screen:panel({
    flex_direction = "row",
    align_items = "center",
    gap = 8,
})
local add = toolbar:button({ text = "Add ball" })
New line: local shake = toolbar:button({ text = "Shake" })
local clear = toolbar:button({ text = "Clear" })
local count = toolbar:label({
    text = "Balls: 0",
    color = theme.token("accent_primary"),
})

local canvas = datumhue.draw.new({
    width = W,
    height = H,
    background = color("#232a2e"),
})
canvas:mount({ parent = screen, width = W, height = H })

local function wall(x, y, width, height)
    local rect = canvas:rect({
        pos = vec2(x, y),
        width = width,
        height = height,
        color = color("#475258"),
    })
    rect:add_body({ type = "static" })
end

wall(-W / 2, -H / 2, W, 10) -- floor
wall(-W / 2, H / 2 - 10, W, 10) -- ceiling
wall(-W / 2, -H / 2, 10, H) -- left
wall(W / 2 - 10, -H / 2, 10, H) -- right

local balls = {}

local function add_ball()
    local x = math.random(-200, 200)
    local y = math.random(0, 120)
    local ball = canvas:circle({
        pos = vec2(x, y),
        radius = R,
        color = color(COLORS[#balls % #COLORS + 1]),
    })
    ball:add_body({
        type = "dynamic",
        shape = "circle",
        restitution = 0.7,
New line:         mass = 1,
    })
    table.insert(balls, ball)
    count.text = "Balls: " .. #balls
end

New line: local function shake_balls()
New line:     for _, ball in ipairs(balls) do
New line:         local kick = vec2(math.random(-200, 200), 400)
New line:         ball:apply_impulse(kick)
New line:     end
New line: end
New line: 
local function clear_balls()
    for _, ball in ipairs(balls) do
        ball:remove()
    end
    balls = {}
    count.text = "Balls: 0"
end

add:on_click(add_ball)
New line: shake:on_click(shake_balls)
clear:on_click(clear_balls)

datumhue.input.on_key(function(key, pressed)
    if key == "a" and pressed then
        add_ball()
    end
end)

for _ = 1, 10 do
    add_ball()
end

In this example: datumhue.color datumhue.theme datumhue.math.vec2 datumhue.physics.gravity datumhue.ui.root UiElement:panel UiElement:button UiElement:label datumhue.theme.token datumhue.draw.new DrawCanvas:mount DrawCanvas:rect DrawPrimitive:add_body DrawCanvas:circle UiElement.text UiElement:on_click datumhue.input.on_key

  • The Shake button joins the toolbar and calls shake_balls when clicked.
  • shake_balls kicks each ball up at 400 pixels per second, and sideways by a random amount.
  • mass = 1 on each ball turns that kick into a speed.

Click Shake a few times. The balls fly up, knock into each other and fall back into a pile.

Try this

  • Set the balls' restitution to 0, then to 1, and watch the pile. Then give the walls a restitution of their own.
  • Tilt gravity with vec2(300, -600).
  • Give Shake a key of its own, as A has for Add ball.

Recap

  • add_body gives a shape a body. A static body stays put; the simulation moves a dynamic one.
  • physics.gravity sets the pull. restitution sets the bounce, averaged between the two bodies that hit.
  • Move a dynamic body with an impulse, never by setting its pos.

New in this step

datumhue.com

(c) 2026 Shuusei AB. Quote excerpts of this manual, with attribution to DatumHue, in your own documentation, tutorials, course materials, reviews, and other writing or video. Republishing it in whole or in substantial part needs written permission: support@datumhue.com.

Victor Mono is licensed under the SIL Open Font License 1.1
Copyright (c) 2024, Rune Bjørnerås (https://github.com/rubjo)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Try

    ↑↓ selectEnter openTab filter

    Settings

    Theme
    Text
    Print

    Keyboard shortcuts

    / or Ctrl KSearch
    ↑ ↓ EnterPick a result
    TabNext result filter
    j kNext or previous entry
    [ ]Previous or next page
    yCopy a link to the current entry
    ?These shortcuts
    EscClose

    On this page