Log inGet started
World

Save Point: Profiles, Levels and Unlocks Kit

README.md

juiceKit

One call makes hits, explosions, pickups and level-ups feel great: Juice.play("explosionLarge", someEntity) shakes the camera, flashes the screen, freezes the action for a beat, squashes the target and plays an effect at the spot, all together and correctly for every player.

Version 1.2.1 (Juice.VERSION). The version, this README and package.yaml move together.

First example

Install the package into any world and put this in a script that runs on every peer (a component on any scene entity works):

local Juice = require("juiceKit.juice")

-- an explosion at an entity: everyone sees it, and each player feels the shake
-- as strongly as their distance to it warrants
Juice.play("explosionLarge", someEntity)

-- or at a point in the world
Juice.play("coinPickup", { 4, 1, 2 })

-- the local player got hurt by an attacker standing at attackerPos:
-- red vignette, a short freeze, a kick away from the attacker (only this player)
Juice.play("hurt", nil, { from = attackerPos })

Nothing else is needed. Requiring juiceKit.juice starts listening for other peers' effects, and the first shake attaches the shake components to whatever camera the scene uses. To make sure a peer whose own scripts never call play still receives world effects, put the JuiceNet component on any scene entity. Its look field also sets the starting look.

Swapping things

Everything goes through the same call, so a different preset, look or strength is a one-word change:

Juice.play("hitLight", enemy)                          -- -> "hitHeavy", "hitCritical"
Juice.play("vfxFire", pos, { look = "pixel" })         -- one effect in another look
Juice.setLook("realistic")                             -- every effect from now on
Juice.play("shakeExplosion", pos, { intensity = 0.5 }) -- half strength, this call only

Presets (51)

Kinds: combo, shake, hitstop, flash, squash and vfx. Strengths: light, medium and heavy. Scope is player (it happens only for the player it is about) or world (every peer sees it). hurt, heal, death, levelUp and landingHard also carry personal = "player": their screen parts play only for a player who is the target, never for whoever called play. See the multiplayer rules below.

namekindstrengthscopepieceswhat it is
coinPickupcombolightworldsquash + vfxA coin sparkle and pulse.
deathcomboheavyworldshake + hitstop + flash + squash + vfxA death: crushed flat, smoke, a slow-motion freeze, and a dark fade for the player who died.
explosionLargecomboheavyworldshake + hitstop + flash + squash + vfxA big blast: fireball, debris, a dust ring, a flash and a shake everyone feels by distance.
explosionSmallcombomediumworldshake + squash + vfxA small blast: fireball, smoke and a distance-scaled shake.
healcombolightworldflash + squash + vfxHealing: rising green motes and a soft green pulse for the healed player.
hitCriticalcomboheavyworldshake + hitstop + flash + squash + vfxA critical: a long freeze into slow motion, a hot flash, a kick away from the attacker and zap sparks.
hitHeavycombomediumworldshake + hitstop + flash + squash + vfxA heavy hit: bigger sparks, a freeze, a strong shake and a flash.
hitLightcombolightworldshake + hitstop + squash + vfxA light hit: sparks, a tiny freeze, a small shake and a wobble.
hurtcombomediumplayershake + hitstop + flashTaking damage: a red vignette, a kick away from the attacker and a tiny freeze.
landingHardcombomediumworldshake + squash + vfxA hard landing: a dust ring, a landing squash and a short heavy shake.
levelUpcomboheavyworldshake + flash + squash + vfxLevel up: a golden column, a ring, confetti, a golden glow and a stretch.
spawncombolightworldsquash + vfxSomething appears: a pop-in with a magic burst.
shakeEarthquakeshakeheavyworldshakeA rolling earthquake that swells, peaks and fades over four seconds for everyone nearby.
shakeExplosionshakeheavyworldshakeA blast shake that every player feels, weaker the farther they are from it.
shakeHeavyshakeheavyplayershakeA strong jolt for big hits and slams.
shakeKickshakemediumplayershakeA directional kick that pushes the view away from where the hit came from (pass from or direction).
shakeLightshakelightplayershakeA quick, small jitter for light hits and footfalls.
shakeRecoilshakelightplayershakeA weapon recoil: the view snaps back and up, then settles.
shakeRumbleshakemediumplayershakeA long, low rumble for engines, collapsing rock or a boss approaching.
hitstopCriticalhitstopheavyplayerhitstopA 180 ms freeze that eases out through slow motion, for critical hits and finishers.
hitstopHeavyhitstopmediumplayerhitstopA 120 ms freeze for heavy blows.
hitstopLighthitstoplightplayerhitstopA 50 ms freeze that lands a light hit.
hitstopSlowmohitstopmediumplayerhitstopHalf a second of 25% slow motion with no freeze, for near misses and dramatic moments.
flashBlackoutflashheavyplayerflashA fade to black and back, for death, respawn or a scene cut.
flashCriticalflashheavyplayerflashA blinding white-orange burst with hot edges.
flashDamageflashmediumplayerflashA red vignette that closes in from the screen edges when you take damage.
flashExplosionflashmediumworldflashA bright blast flash every player near the explosion sees.
flashFreezeflashlightplayerflashAn icy blue vignette for frozen, chilled or shielded.
flashHealflashlightplayerflashA soft green pulse from the edges.
flashHitflashlightplayerflashA sharp white flash across the screen.
flashLevelUpflashmediumplayerflashA warm golden glow that blooms and fades.
flashPoisonflashlightplayerflashA sickly purple-green vignette for poison and curses.
flattensquashheavyworldsquashCrushed flat, held, then springs back up, for deaths and stomps.
jellyWobblesquashlightworldsquashA jelly wobble when something is hit.
popInsquashmediumworldsquashGrows from nothing with an overshoot, for spawns and pickups appearing.
pulsesquashlightworldsquashA quick uniform bump for collect, select or a heartbeat.
punchsquashheavyworldsquashA hard punch inward that rings out, for heavy impacts.
squashLandsquashmediumworldsquashFlattens on landing and springs back.
stretchJumpsquashmediumworldsquashStretches tall on take-off and settles.
vfxCoinvfxlightworldvfxA coin sparkle.
vfxConfettivfxmediumworldvfxA confetti burst.
vfxDustvfxlightworldvfxA dust puff.
vfxExplosionLargevfxheavyworldvfxA large explosion: fireball, debris and a smoke ring.
vfxExplosionSmallvfxmediumworldvfxA small explosion.
vfxFirevfxmediumworldvfxA burst of fire.
vfxHealvfxmediumworldvfxRising healing motes.
vfxLevelUpvfxmediumworldvfxA level-up column and ring.
vfxMagicvfxmediumworldvfxA magic burst.
vfxSmokevfxmediumworldvfxA smoke cloud.
vfxSparksvfxlightworldvfxImpact sparks.
vfxZapvfxmediumworldvfxAn electric zap.

Every vfx preset and every combo's effect is drawn in the current look: cartoon (solid toon shapes, the default), realistic (soft additive glow, smoke and dark debris), pixel (chunky cubes snapped to a grid) or scifi (cyan and magenta energy). Effect kinds: sparks, dust, explosionSmall, explosionLarge, magic, heal, levelUp, coin, smoke, fire, zap and confetti.

Interface (require("juiceKit.juice"))

Playing

Juice.play(name, target?, opts?) -> result plays a preset. It raises on an unknown preset, look or target, and otherwise returns a table saying what ran on this peer: { shake = strength, hitstop = true, flash = alpha, squash = true, vfx = particleCount, sent = true, id = playId }. Every play gets an id, even one that intensity 0 turned into nothing, so the result can always be handed to Juice.stop.

  • target: an entity, an entity id, an entity name, a position ({x,y,z}, {x=,y=,z=} or a vector), or nil for the local player.
  • opts:
optionmeaning
intensityMultiplier for this call (multiplied by the global intensity).
lookDraws this call's effect in a look other than the current one.
fromThe attacker: an entity or a position. Kicks push away from it, and when the target is a thing (not a player) and from is another player's avatar, the personal parts land on that attacking player's screen.
directionWorld direction the hit travels, used instead of from.
scaleEffect size multiplier.
axisSquash axis: "y" (default), "x" or "z".
scope"auto" (default): world parts go to every peer, personal parts to the one player they belong to. "local": play here only what belongs on this peer and send nothing, for code that already runs on every peer. "world": also send a player preset's world parts to every peer.
seedSeed for a repeatable effect.

Juice.stop(what) -> boolean stops one play early and leaves everything else running. what is the table play returned, its id, or a preset name; a name stops every play of that preset on this peer, its own and ones received from other peers.

local charge = Juice.play("shakeRumble")
-- the charge was cancelled:
Juice.stop(charge)
  • The shake comes off the camera with no drift; other shakes keep going.
  • The hitstop lets go: normal speed comes back at once unless another hitstop still holds.
  • The flash disappears, the squash lands on the exact base scale, and the effect's particles and light vanish.
  • Stopping a play this peer sent to others stops it on their screens too.
  • It returns false for a play that has already finished or was stopped, and for nil. An unknown preset name raises.

Juice.isPlaying(what) -> boolean says whether any part of a play (same what as stop) is still running here.

Juice.stopAll() stops every shake, hitstop, flash, squash and effect at once, puts squashed things back at their exact base scale, and releases the time scale. It acts on this peer only and forgets every play id.

Finding presets

  • Juice.list(filter?) -> rows returns every preset as { name, kind, strength, scope, personal, looks, pieces, effects, tags, custom, description }, sorted by kind and then name.
    • A kind name string ("shake", "combo", …) keeps that kind.
    • Any other string matches a tag or a name ("heavy", "world", "explosion", "custom").
    • A table { kind?, strength?, scope?, look?, piece?, tag?, custom? } requires all of its fields.
  • Juice.names(filter?) -> { string } returns the same rows as list, names only.
  • Juice.get(name) -> row? returns one row plus spec, the resolved pieces. Both are copies: changing them never changes the preset.
  • Juice.has(name) -> boolean says whether a preset by that name exists.
  • Constants: Juice.KINDS, Juice.STRENGTHS, Juice.SCOPES and Juice.PIECES.

Making your own

Juice.define(name, spec) -> row adds a preset, or replaces one you defined earlier. Each piece in spec is either the name of an existing preset of that kind or a table of its own:

Juice.define("bossSlam", {
    shake = "shakeEarthquake", hitstop = "hitstopHeavy", flash = "flashExplosion",
    squash = "punch", vfx = { kind = "explosionLarge", scale = 1.6 },
    strength = "heavy", scope = "world", tags = { "boss" },
    description = "The boss hits the floor.",
})
Juice.play("bossSlam", boss)

Besides the pieces, spec takes kind, strength, scope ("player" or "world", worked out from the pieces when left out), personal ("target", the default, or "player" for moments that only make sense for a player; see the multiplayer rules), tags and description.

Your presets can be built on each other (Juice.define("bossSlamBig", { shake = "bossSlam", vfx = { "bossSlam", "confetti" } })), and changing one never breaks another:

  • Juice.remove(name) -> boolean removes a preset you defined (false when there was none). Presets built on it keep working exactly as before: each keeps its own copy of the pieces it took from it.
  • Redefining a preset changes what the presets built on it play, except for a piece the new version no longer has: those keep the piece they had.
  • define and remove refuse a change that would leave another preset broken, such as two presets naming each other in a loop. They raise juiceKit.define: 'a' would break 'b': … (or 'a': … when a itself would break), and every preset stays as it was.

Settings

callwhat it does
Juice.setLook(name) / getLook() / looks() / hasLook(name) / vfxKinds()The one look switch every effect follows.
Juice.setIntensity(x) / getIntensity()Global intensity, clamped to 0–2. It scales shake, flash, hitstop and squash strength and effect density; 0 turns the kit off.
Juice.setReduceMotion(on) / getReduceMotion()Motion-sickness comfort: no camera shake at all, and gentler, shorter flashes. Hitstop, squash and effects still play.
Juice.stats()Counters and live counts from every piece, plus recent, the last 12 plays and receives with who got the personal parts, for HUDs, tests and debugging.

Settings are per peer, so each player chooses their own look, intensity and comfort.

Multiplayer

The world is always multiplayer, and play routes each piece for you. Every preset is made of two kinds of parts:

  • World parts happen at a spot: the visual effect, the squash, a blast shake (one with distance falloff), a blast flash (one with a radius) and a blast's hitstop. For a world-scope preset they run here and on every other peer. Each peer works out its own shake, flash and freeze from its own distance to the spot. A far player sees the blast without being shaken. Only players within roughly the inner third of the shake's range freeze.
  • Personal parts belong to one player's screen: a fixed camera shake, a screen flash and a hitstop. They play for exactly one player, never for everyone:
targetwho gets the personal parts
nil, or your own avataryou
another player's avataronly that player (it is sent to them)
a thing (an NPC, a prop) or a pointyou, or the attacking player when opts.from is another player's avatar
a thing or a point, for a preset with personal = "player"nobody: these moments only make sense for a player

The presets with personal = "player" are hurt, heal, death, levelUp and landingHard. A healer never sees the healed player's green pulse, and a killer never gets the victim's blackout. A hit (hitLight, hitHeavy, hitCritical) on an NPC lands on the attacker's screen; on another player it lands on theirs.

  • Squash on a shared object: a synced entity owned by another peer is squashed by its owner, who receives the same play, and its scale reaches everyone from there. Peers never write to an entity they don't own.
  • scope = "local" plays here only what belongs on this peer and sends nothing. Use it from code that already runs on every peer (for example, reacting to a synced health field): each peer then gets exactly its own share.
  • Juice.stats().recent shows, for the last few plays and receives, who got the personal parts ("here", "nobody" or the recipient avatar's id) and what ran.
  • Stopping travels like playing: Juice.stop on a play this peer sent also sends a small stop message, and each peer that received the play stops exactly that one (matched by sender and play id). Stopping by name stops received plays of that name on your own screen only. A peer on a version before 1.1.2 ignores the stop and lets its share finish.

Guarantees

  • No camera drift: the shake is added after every camera controller has run and removed before they run again. Measured on all nine builtin controllers (orbital follow, third person follow, first person, orbit, chase, side scroller, bird's eye, isometric and RTS): the camera returns to exactly where it would have been (0.000000 m of drift).
  • Hitstop never sticks: it is one owned time-scale hold. The slowest live request wins, and every span is capped (no freeze longer than 0.6 s). It always releases on end, on stopAll, on interruption and on reload.
  • Cheap and self-cleaning: particles are pooled instanced draws, capped at 700 live, with the oldest stolen first. Lights come from a pool of 4. Nothing is spawned per particle, and everything drains to zero and idles when quiet.
  • Flashes are part of the picture: they are drawn by one post-process pass over the lit scene, before the UI, so your HUD stays on top and untinted. The pass is switched off whenever no flash is playing. A copy of the module left behind by a hot reload can never switch it back on.
  • Never touches the editor: the shake only moves the gameplay camera in play mode, never the editor's fly-camera. A peer drops plays sent by other peers until its own scene has arrived.

Pieces (for advanced use)

The juice module is the front door. The modules under it can be used directly:

modulewhat it holds
juiceKit.shakeAdditive camera shake layers (noise, kick, rumble, quake) with distance falloff.
juiceKit.hitstopOwned, capped time-scale holds.
juiceKit.flashFull-screen flashes, vignettes and glows, drawn into the rendered picture by one post-process pass under the UI.
juiceKit.squashSquash-and-stretch springs that always return to the base scale.
juiceKit.vfxPooled particle effects: 12 kinds in 4 looks.
juiceKit.netThe juiceKit.play message channel.
juiceKit.presetsThe data: presets, looks, palettes and effect recipes.
juiceKit.utilSmall vector, quaternion and targeting helpers.

Components: JuiceNet (optional; listens from scene load and sets the starting look), JuiceShakeApply and JuiceShakeRestore (attached to the camera automatically). Assets: juiceParticle.shader, juiceFlash.shader and the juiceSolid, juiceGlow and juiceSmoke materials.

Tests

Run them the standard way, in edit mode: tools.use("tests", "run", "juiceKit") (the shell form is zero tests run juiceKit). The suite is named juiceKit, not juiceKit.testSuite. You can also run it directly with asset.resolve("juiceKit.juiceKit", "testSuite"):run(). 104 tests cover every public call. They pass on repeated runs, either way, with or without a player or a scene camera:

  • Playing: every target form, and exactly what a play reports.
  • Listing: every filter, the sort order, and the copies list and get hand out.
  • Defining your own presets: broken specs are refused, defaults are worked out, redefining replaces, and presets build on presets.
  • Presets built on presets: removing or redefining a base keeps its dependents playing the same thing, a chain survives losing its root and then its middle, and loops are refused with the old preset intact.
  • Looks: each look's material and shape, and a look given to one play.
  • Intensity: flash alpha, shake strength, particle count and hitstop length.
  • Reduce motion: no shake, gentler flashes.
  • Stopping early: stopAll mid-shake, mid-hitstop, mid-squash, mid-flash and mid-effect.
  • Stopping one play: Juice.stop and Juice.isPlaying by result, id and name. Tested per piece (one shake, hitstop, flash, squash or effect stopped while another keeps going) and on whole combos, and a stop sent to and received from another peer reaches only that play.
  • Multiplayer routing: another player's flash and hitstop never land on the caller, blasts are scaled by distance, and squash is left to the owner.

Watch out for

  • Play from code every peer runs, or from one peer with the default scope. By default (scope = "auto") play sends the world parts to everyone. If the same call already runs on every peer (for example, a reaction to a synced health value), pass scope = "local", or each peer receives it once per sender.
  • Shakes only move the camera in play mode. In edit mode Juice.play still runs the effects, flashes and squashes, but it never touches the editor's fly-camera.
  • The flash is a post-process pass. It tints the scene camera's picture, under your UI. If you want a flash over the UI (a menu fade), use a UI screen instead.
  • Heavy scenes slow down joiners. Every entity a scene bakes in is replicated in play, and a joining peer receives them all as one snapshot before its gameplay starts. Keep static scenery light, or spawn it from code each peer runs, so new players get in quickly.
  • Reduce motion is per peer. It is a comfort setting for the player at this screen. Set it from that player's own options, not from shared state.

Known issues

These are engine problems met while building the kit. The kit already works around each of them; they are listed so a creator who meets one knows what it is.

  • The standard test runner has no player and no scene camera. tests.run runs a suite in edit mode, with no avatar, an empty scene and fallback lighting, and in edit mode the camera on screen is the editor's. The kit's "where am I" (U.herePos) falls back from the avatar to the gameplay camera, then to the camera on screen, then to the world origin, so the suite passes either way.
  • tests.run takes the suite's asset name. That is juiceKit; juiceKit.testSuite is not found. A top-level Test.afterEach registers nothing, so each describe installs its own clean-up.
  • A test run frees GPU buffers and draws mid-suite. The kit's particle pools detect it and rebuild. A buffer handle's :destroy() does not free the GPU buffer; substrate.destroyBuffer does.
  • Joiners and OwnerOnly camera rigs. A player prototype's camera rig is OwnerOnly, so when a joiner's spawn runs on another peer, the joiner receives its body but no camera of its own. A desktop joiner then stays on the editor's free camera (which does not draw game UI, so no HUD), and a web joiner gets a default camera pointed away from the scene. The showroom's Gallery checks every peer: if no camera follows that peer's player, it gives the player a local orbital follow camera behind them, facing the stage, and hands it the viewport. It also starts each player on the spawn, facing the stations. The kit itself drops plays received before a peer's gameplay starts.
  • play as <name> shares the peer. Two agent sessions in one engine are one peer, so a real second player needs a second client (another desktop session or the web).
  • Post-process properties stay stale after a shader edit. Editing a shader's properties.yaml recompiles it, but an already-registered effect keeps its old property list until it is removed and added again. postprocess.setProperty also returns true for a property the effect never declared.
  • The post-process chain also applies to offscreen captures and render-to-texture cameras. Flashes are short, so this rarely matters. While a flash is live, highlights brighter than white are clamped.
  • Harmless warnings. The code checker reports asset-unresolved for ~.JuiceShakeApply, ~.JuiceShakeRestore, ~.juiceSolid and ~.juiceFlash; they all resolve when running.
  • Small API traps.
    • entity.exists raises when given a live entity's name; pass an id.
    • _G is sealed.
    • A local named after an engine namespace (live, av) hides that namespace.
  • Publishing. After a push the search index can show the previous version's description for a while. A world's store body cannot be read back, only replaced.