Log inGet started
World

Toy Box Course: Trampolines, Bumpers, Fans, Breakables and Pickups Kit

Branchmain
Branchesmain
Commitafd3b642d6

README.md

courseToys: Toy Box Course kit

Fun physics toys to tumble into, for any course and any dynamic rigid bodies (ragdolls included): trampolines, jelly pads, kicker ramps, breakable glass panes, breakable crates, bowling pins, pinball bumpers, boost fans, launch pads, coin trails, bonus zones, slow‑motion rings, spinning bars, see‑saws, gongs and bells, balloon clusters, piñatas / mystery boxes, magnets and conveyors. 19 kinds, each drawn in 11 looks (the ten course themes rooftops, library, candy, haunted, ice, neon, clouds, forge, jungle, clockwork, plus default), each with its own synthesised sounds. Built for Tumblestep: The Endless Stair (push a ragdoll down an endless staircase, every impact scores) and for anyone who wants playful obstacles along a track, a run or a stunt course.

Version 1.1.2 (Toys.VERSION).

What changed in 1.1.2

  • Toys.defaultWeights() answers a copy of the per-kind weights populate picks by, so a game can scale them (local w = Toys.defaultWeights(); w.glass *= 2; w.pinata = 0) and pass the table as opts.weights.

What changed in 1.1.1

  • parent no longer throws toys off the course. spawn passed pos straight to the parent's space, so slots in world space (the convention populate and endlessStairs chunks use) landed at parent + slot: in Tumblestep, toys on a chunk 516 m down stood 255-412 m to the side and 80-225 m below the stair. Now pos and yaw are WORLD values also when a parent is given: spawn converts them into the parent's space (inverse of its position, rotation and scale; the parent's yaw is taken off yaw). Pass localPos = true to give pos and yaw in the parent's space instead. populate with parent is fixed with it, and the README example now works as written. Test: courseToys_parent populates a chunk 400 m down with parent = chunk.root (root unrotated and turned 35 degrees): every toy is within slot.width/2 + 1 m of a slot.
  • Contacts cannot go silent for a session. The world contact listener and the physics step hook are now registered per play session: every mode change bumps a session counter, the next spawn / listen re-registers (dropping the old handle), and on entering play the kit re-registers for toys that were spawned before. Toys.stats() now also reports handlers (toy colliders listened for), handlerHits (contact records that found a toy) and listening (the listener belongs to this session), so a game can tell "contacts arrive but touch no toy" from "nothing listens".

What changed in 1.1.0

  • populate guarantees variety. It is now a distance-driven director: toys are spaced by metres, each pick strongly favours the kinds the last 150 m has not shown, no kind appears more than twice in a row, coin trails come on their own beat, surprises (piñata, slow-mo ring, magnet, bonus zone) are rare but guaranteed now and then, and the deeper the course goes the denser it gets and the rarer kinds unlock (depth / difficulty). Its history is kept across calls, so a game that populates chunk by chunk gets the same variety as one long call (1.0.x reset every call and could place nothing but crates for hundreds of metres on step-only stretches). Side and overhead toys (fan, gong, magnet, piñata) now also fit on steps; balloons, slow-mo rings and coins fit over gaps.

  • Measured on synthetic course slots, 2 km populated in 40 m calls: every 150 m window held 7 to 13 kinds (6 or more without counting coins; average 9.4), never more than 2 of one kind in a row, a coin trail every 24-40 m (longest gap 72 m), 12 surprises (the first at 451 m), and the last 300 m held 38 toys of 11 kinds against 25 toys of 9 kinds in the first 300 m. On a course of steps only: still 7+ kinds in every window.

  • Runtime meshes checked: 0 of 66,240 triangles over all 62 kind-and-theme meshes wind against their normals.

  • New: Toys.newPopulateState(), Toys.resetPopulate(stream?), the set-up-course-toys workflow.

  • Works with any dynamic rigid body. Tell the kit which bodies belong together (setBodyGroup) and a bounce, a boost, wind or a magnet changes the whole group's velocity alike, so a ragdoll is thrown as one piece and never torn apart.

  • Every interaction is reported once: events are debounced per toy and body group, and zones keep one visit per group even when a tumbling ragdoll flickers across their edge.

  • Local by default: toys are spawned on this peer only (synced = false), so every player in a multiplayer world has their own course of toys.

  • Constant memory over a long run: meshes are built once per kind and theme and shared; debris (glass shards, planks) and confetti clean themselves up with a hard cap; despawn removes everything a toy made.

  • Cheap: one world contact listener with a table dispatch (no per-toy listeners), visual animation at 30 Hz near the camera under a time budget. Measured with 209 toys and falling dummies: under 1 ms a frame of kit time on desktop.

  • No dependency on a course kit: populate takes generic placement slots.

Install

Search ZeroMind for courseToys (or "trampolines bumpers breakable glass toys") and install courseToys.package, or by guid. It brings juiceKit (particle puffs; optional at runtime) and its mesh builder (geometry, from trophyKit).

local Toys = require("courseToys.toys")

Open the gallery scene to see every kind in every theme: zero scene load courseToys.gallery (press Play and ten-box dummies rain on the first row).

Quick start

local Toys = require("courseToys.toys")

-- which bodies belong together (your ragdoll's bones), and which may trigger toys
Toys.setBodyGroup(function(id) return myRagdoll.bodiesOf(id) end)   -- list of ids, or nil
Toys.setFilter(function(id) return myRagdoll.isPart(id) end)

-- place some toys
local tramp = Toys.spawn("trampoline", { pos = { 0, 0, 6 }, yaw = 0, theme = "candy" })
Toys.spawn("glass", { pos = { 0, 0, 12 }, theme = "haunted" })
Toys.spawn("coins", { pos = { 0, 0, 14 }, theme = "candy", params = { to = { 0, -2, 8 }, count = 8, arc = 1.5 } })

-- score what happens
Toys.on("bounce", function(ev) addScore(10 + ev.speed) end)
Toys.on("collect", function(ev) addCoins(ev.value) end)
Toys.on("surprise", function(ev) print("surprise!", ev.value) end)   -- the game decides the reward

API

callwhat it does
Toys.kinds()list of { id, name, description, tags }
Toys.themes()list of theme ids ("default" is also accepted by spawn)
Toys.spawn(kind, opts) -> handleopts: pos {x,y,z}, yaw (radians, +Z is the toy's forward), theme, scale (1), seed, parent, localPos (false), synced (false), params (per kind, below), shadows (true). pos and yaw are world values, also with a parent (the kit converts them into the parent's space); localPos = true reads them in the parent's space. Answers { id, kind, root, theme } (root is the toy's root entity)
Toys.despawn(handle)removes the toy and everything it made
Toys.clear()removes every toy, debris, particle and sound voice
Toys.on(event, fn) -> unsubscribeevents: "hit", "bounce", "break", "collect", "enter", "exit", "boost", "slowmo", "surprise", or "*" for all
Toys.setBodyGroup(fn)fn(entityId) -> { ids } or nil: bodies that move together (a ragdoll)
Toys.setFilter(fn)fn(entityId) -> boolean: which bodies may set toys off
Toys.populate(slots, opts) -> handlesplaces a varied, fair mix on placement slots { pos, forward, right, width, kind = "step" | "landing" | "ramp" | "gap", dist? } (endlessStairs chunk slots fit as they are). See populate below
Toys.defaultWeights() -> { [kind] = w }a copy of the per-kind weights populate picks by; scale or zero entries and pass the table as opts.weights
Toys.newPopulateState() / Toys.resetPopulate(stream?)a separate populate history (pass as opts.state) / forget a stream's history when a run restarts (a slot list that starts 50 m or more behind the last one also starts a new run by itself)
Toys.list(kind?), Toys.stats()live handles; counts, the kit's measured cost (stepMs, contact time, contactEvents) and the listener's health (handlers, handlerHits, listening)
Toys.warm(kinds?, themes?)pre-builds looks so the first spawn of each costs nothing
Toys.setVolume(v), Toys.setEffects(on)sound volume (0 mutes), particle puffs on/off
Toys.applySlowmotrue (default): slow-mo ring and piñata slow-mo hold the engine time scale; set false to only report it

Event ev: { event, kind, toy (handle), body (entity that touched), group (ids), groupKey, point {x,y,z}, impulse, speed, value }. value per event: bounce the launch speed, break "glass"/"crate"/pins knocked down/1 per balloon/"pinata", collect the coin value, enter/exit the zone value (bonus multiplier, fan strength, magnet strength), slowmo the time scale, surprise the surprise id (coinShower, megaBounce, gravityFlip, slowmo, jackpot) with ev.data details. hit is any solid contact, once per toy and group per cooldown.

populate

course:on("chunkSpawned", function(chunk)
    -- chunk.slots are world positions; with `parent` the toys are converted into the
    -- chunk root's space, so they follow the chunk (rebase, despawn) and stay on its slots
    chunk.toys = Toys.populate(chunk.slots, { theme = chunk.theme, seed = chunk.index, parent = chunk.root })
end)
optdefaultmeaning
theme, scale, parent, syncedas for spawn
seed1the dice for this call (same slots, history and seed give the same toys)
density1more (2) or fewer (0.5) toys; divides spacing
spacing11metres between toys at depth 0 (a third less at full depth), randomised ±30 %
weightsbuilt in{ [kind] = w }, 0 removes a kind
depth / depthScaleeach slot's dist / 1500how deep a slot is: depth + slot.dist over depthScale metres gives the difficulty 0..1
difficultynila fixed difficulty 0..1 instead of one from depth
rarity1scales the surprise kinds (piñata, slow-mo ring, magnet, bonus zone) and how often one is guaranteed
surpriseEvery220metres after which a surprise is guaranteed (never two within 90 m)
coinEvery32metres between coin trails (±25 %); coins = false turns them off
window / minKinds / maxRepeat150 / 5 / 2the variety rule: in any window metres show at least minKinds kinds; never more than maxRepeat of one kind in a row
stream / state"default"which history to continue (one per course or player)

Unlock depths (difficulty): trampoline, crate, bumper, glass, balloons, kicker, gong, fan from the start; jelly and pins 0.1, launch pad 0.15, conveyor 0.2, see-saw 0.25, piñata and bonus 0.3, spinner 0.35, slow-mo 0.4, magnet 0.45 (Toys.POPULATE_UNLOCK). Each ramps in over 0.15, and the rarer kinds grow more common the deeper it goes. Slots without dist use the distance between slot positions and unlock everything from the start.

Kinds and their params

kindeventsmain params (defaults)
trampolinehit, bounceboost 7, restitution 0.85, minUp 8, maxUp 26, forward 0, cooldown 0.35
jellyhit, bounceboost 3.5, restitution 0.55, grip 0.45 (sideways speed kept), maxUp 14
kickerboostspeed 11, extraAngle 0.35 rad, gain 1
glasshit, breakminSpeed 2.5 (slower just bumps), keep 0.8 (speed kept going through), debrisLife 2.6, respawn (seconds, off)
cratehit, breakminSpeed 3, minImpulse 60, mass 12, static false, pieces 8, value
pinshit, break (value = pins down)rows 4 (10 pins), pinMass 1.6, settle 1.6 s
bumperhit, bouncekick 11, lift 2.5
fanenter, exit, booststrength 26 m/s², length 7, lift 0.15
launchpadenter, exit, boostspeed 12, up 9
coinscollectto {x,y,z} + count 8 + arc, or points (local list); value 1, gemEvery 0, gemValue 5
bonusenter, exitmultiplier 2 (drawn on the sign)
slowmoenter, exit, slowmotimeScale 0.35, duration 1.4 s, apply true
spinnerhitspeed 1.6 rad/s, direction 1, swat 1.3, lift 2
seesawhitmass 30
gonghit (value = loudness 0..1): (bell look in library, clockwork, haunted, ice, candy, clouds)
balloonsbreak (one per balloon)count 5, lift 2.5
pinatahit, break, surprisesurprise (force one), surprises (weighted list), applySurprise true, hitsToBreak 3, megaUp 22, flipTime 1.4, showerCoins 10, jackpot 50
magnetenter, exitradius 6, strength 20, repel false
conveyorhit, enter, exit, boostspeed 4 m/s

Kinds × themes

Every kind shares its mechanism across themes and swaps shape, material and colour so it belongs to the theme.

kindrooftopslibrarycandyhauntediceneoncloudsforgejungleclockwork
trampolinestriped mattress, chimneysopen bookmarshmallow on a biscuitcoffin lidfrozen drumglowing ring padcloud + rainbowriveted leather bellowsgiant mushroombrass spring drum
jellylime jellyjam jellypink gummy + cherrygreen slime with eyesblue slushmagenta jellypink jelly + cherrymolten jelly with embersmoss jelly on bambooteal jelly
kickertiled roof + gutterleaning bookchocolate bargravestone slabice slopeglowing chevronsrainbow rampriveted ironlog rampbrass + gear
glasswindow with mullionsstained-glass archsugar-glass, candy framecracked arched windowsheet of iceholo panerainbow glassiron-bandedbamboo + vineclock face (round)
cratewooden cratestack of tomesgift box with bowcrate with skullice block with fishholo cubegift boxiron-banded cratebamboo-cornered cratebrass crate + gear
pinstraffic-cone pinscream/red pinscandy-stripedbone pinsice pinsglow-ringed pinsstar pinsbrass pinswooden pinsbrass pins
bumperwater tankinkwell + quillcupcakejack-o'-lanternsnowball + iciclesneon ringcloud + starcast ironbig flowergear
fan, launchpad, coins, bonus, slowmo, spinner, seesaw, gong, balloons, pinata, magnet, conveyorthemed colours, materials, ornaments (chimneys, books, gumdrops, candles & skulls, icicles, glow orbs, cloud puffs, anvils & embers, leaves & flowers, gears) and per-theme shapes: candy-cane spinner, clock-hand spinner, bells vs gongs, ghost balloons, star / pumpkin / brass-egg / "?" piñatas, gear and star coins, snowflake coins

default is a bright primary-colour toy box.

Contents

assetwhat
toys.modulethe API above
looks.moduleevery kind's look per theme (procedural meshes, cached)
shapes.modulebevelled solids over geometry (rounded boxes, cylinders, tori, wedges, gears, stars, glyphs)
themes.moduletheme palettes (roles: body, trim, pad, soft, accent, pop, metal, dark, light, glow) and materials
sfx.modulethe synthesised sounds (Sfx.bake() re-bakes them) and a pooled spatial voice player
showcase.modulethe gallery grid, the ten-box test dummy and runTest
gallery.sceneevery kind in every theme
materials/toy paint, gloss, satin, matte, metal, glass, ice, jelly, aura and ten glow colours
sounds/23 sound clips
guidesHow to add trampolines, bumpers and breakable glass to my game, Example: make a pinball ragdoll obstacle course

Known limits

  • Toys react to dynamic rigid bodies. A CharacterController player has no rigid body; to bounce one, read the events and drive it yourself (airMotor works well).
  • Toys are posed by pos and yaw in world space, also with a parent (since 1.1.1; 1.1.0 read them in the parent's space, which put toys on any chunk away from the origin far off the course). Pass localPos = true for parent-local values. The kit's launch directions use the toy's world yaw at spawn, so a parent that turns afterwards turns the drawing but not the launch direction.
  • The kit listens to every contact in the world through one listener (cheaper than per-toy listeners in this engine); events are recorded for every contact pair while toys exist.