Back to the referencePhysics
The body format the engine defines and the seam an adapter registers through. The simulation lives in the adapter.
85 symbols
#createPhysicsBody2dfunctionnacatamalon
createPhysicsBody2d(options: { id, name, body, collider } & Partial<TPhysicsSurface>) => TPhysicsBody2d
A complete flat collider from a partial description.
The factory exists so that "a rectangular collider" is one call instead of six fields somebody can
forget: every record that reaches a document is complete by construction, which is what lets
the format promise that a scene means the same thing whoever simulates it.
Parameters
options{ id, name, body, collider } & Partial<TPhysicsSurface>What is known: at least its shape. Everything left out takes its default.
View source · physics/new_physics_body.ts:47#createPhysicsBody3dfunctionnacatamalon
createPhysicsBody3d(options: { id, name, body, collider, offset } & Partial<TPhysicsSurface>) => TPhysicsBody3d
A complete collider in three dimensions from a partial description: the sibling of
createPhysicsBody2d, filling in the same defaults.
Parameters
options{ id, name, body, collider, offset } & Partial<TPhysicsSurface>What is known: at least its shape. Everything left out takes its default.
View source · physics/new_physics_body.ts:68#createRetroBody2dfunctionnacatamalon
createRetroBody2d(options: { id, name, body, collider } & Partial<Omit<TRetroSurface, 'solidSides'>> & { solidSides }) => TRetroBody2d
A complete retro collider from a partial description: the sibling of createPhysicsBody2d, so
every record that reaches a document is complete by construction.
Parameters
options{ id, name, body, collider } & Partial<Omit<TRetroSurface, 'solidSides'>> & { solidSides }What is known: at least what it is and its shape. Everything left out takes its
default.
View source · physics/new_retro_body.ts:48#usePhysicsBody2dfunctionhooknacatamalon
usePhysicsBody2d(options: TPhysicsBody2dOptions) => TPhysicsBody2d
Gives this object a flat shape to collide with.
It does two things, and that is the whole design. It writes down what the object is made of,
so a scene saved from code says it and comes back with it; and it hands that to whatever is
installed to simulate, so it moves. One way in, whether the scene was typed by a person or opened
from a file, which is what makes those two behave the same.
Where it is comes from the object, never from here: the object's own placement if it has one, and
otherwise the placement of what it draws, which is where you put it with createSprite.
With nothing installed to simulate, this is still worth calling: the shape is recorded, the scene
opens and saves without losing it, and it sits still. That is what a tool wants while somebody is
building a level.
Parameters
optionsTPhysicsBody2dOptionsIts kind ('dynamic', 'static' or 'kinematic'), its shape, and what it is
made of.
Example
const BROWN = getColor('#8b5a2b');
const Crate = (x: number, y: number) => {
createSprite({ tint: BROWN, width: 24, height: 24, transform: { x, y } });
usePhysicsBody2d({ body: 'dynamic', collider: { shape: 'rect', width: 24, height: 24 }, bounce: 0.2 });
};
View source · hooks/physics/use_physics_body.ts:80#usePhysicsBody3dfunctionhooknacatamalon
usePhysicsBody3d(options: TPhysicsBody3dOptions) => TPhysicsBody3d
Gives this object a shape in three dimensions to collide with. The sibling of
usePhysicsBody2d; see it for why declaring and simulating are one call.
offset is where the shape sits inside the object, which is what a model imported standing on
its own feet needs so that its collider is not buried half in the floor.
Parameters
optionsTPhysicsBody3dOptionsIts kind ('dynamic', 'static' or 'kinematic'), its shape, and what it is
made of.
View source · hooks/physics/use_physics_body.ts:136#usePhysicsWorld2dfunctionhooknacatamalon
usePhysicsWorld2d(options: { id, gravity }) => TPhysicsWorld2d
Opens the flat simulation for this scene, and says how hard things fall.
Called in the scene's body, because gravity belongs to the scene and not to anything in it: a
scene seen from above has none and a platformer does. Called anywhere else it is recorded on that
object and nothing reads it, which is said out loud rather than ignored.
gravity is in pixels per second squared with +y pointing down, which is the way a sprite's
y axis grows, so earth-ish is about 900 and positive.
Like a collider, this is worth calling with nothing installed to simulate: the scene records what
it wants and comes back with it.
Parameters
options{ id, gravity }How hard things fall (gravity, in pixels per second squared, +y down), and an
id for a scene with more than one.
Example
export const Level: TSceneFn = () => {
usePhysicsWorld2d({ gravity: { x: 0, y: 900 } });
// ...then objects with usePhysicsBody2d, which fall in it.
return createScene();
};
View source · hooks/physics/use_physics_world.ts:39#usePhysicsWorld3dfunctionhooknacatamalon
usePhysicsWorld3d(options: { id, gravity }) => TPhysicsWorld3d
Opens the simulation in three dimensions for this scene. See usePhysicsWorld2d.
gravity is in metres per second squared with +y up, so earth is -9.81: the opposite sign
from the flat one, because there a placement's y grows downwards. The two disagree on purpose.
Parameters
options{ id, gravity }How hard things fall (gravity, per second squared), and an id for a scene
with more than one.
View source · hooks/physics/use_physics_world.ts:85#useRetroBody2dfunctionhooknacatamalon
useRetroBody2d(options: TRetroBody2dOptions) => TRetroBody2d
Gives this object a retro body: one that never turns, moved in pixels a fixed step at a time and
stopped against the others axis by axis, the way the old games did.
It does what usePhysicsBody2d does for the full simulation, and nothing else: it writes down
what the object is, so a scene saved from code says it and comes back with it, and hands it to
whatever is installed to move it (installRetroPhysics2d() from nacatamalon/retro-physics2d).
An object has one body, so this replaces a collider of the full simulation on the same object.
With nothing installed, the body is still recorded and the scene opens and saves with it; it sits
still.
Parameters
optionsTRetroBody2dOptionsWhat it is ('dynamic', 'static' or 'kinematic'), its shape, and how it
moves.
Example
const Ball = (x: number, y: number) => {
createSprite({ key: 'ball', transform: { x, y } });
useRetroBody2d({ body: 'dynamic', collider: { shape: 'circle', radius: 4 }, bounce: 1, gravityScale: 0 });
};
View source · hooks/physics/use_retro_body.ts:60#useRetroWorld2dfunctionhooknacatamalon
useRetroWorld2d(options: Partial<Omit<TRetroWorld2d, '_type'>>) => TRetroWorld2d
Opens the retro simulation for this scene, and says how hard things fall: in pixels per second
squared with +y down, like the full flat simulation's.
Called in the scene's body, because gravity belongs to the scene. A scene has one world, of
whichever kind, and its bodies are the ones that world moves.
Parameters
optionsPartial<Omit<TRetroWorld2d, '_type'>>How hard things fall (gravity), where its edges are (bounds, the screen when
left out), how fast its time goes (timeScale), and an id to keep a document's.
Example
export const Level: TSceneFn = () => {
useRetroWorld2d({ gravity: { x: 0, y: 900 } });
// ...then objects with useRetroBody2d, which fall in it.
return createScene();
};
View source · hooks/physics/use_retro_body.ts:119#useTileBody2dfunctionhooknacatamalon
useTileBody2d(options: TCharacterShape2d) => TCharacterBody2d
Makes this object a platformer's character that walks on the scene's maps, with no physics engine:
the game says how fast it goes, and the map stops it at walls, holds it on ledges and slopes, lets
it climb ladders and carries it on belts.
The classic way, in pixels. It moves across, settles against walls, then up or down, settles
against the floor or the ceiling, the way the old platformers did, with nothing to load and the same
result on every machine at a fixed step. It knows the maps, and the objects laid out with a 2D
collider that never moves (a 'static' body that is not a sensor: a floor, a wall, a platform made
of an object rather than of tiles), measured as the rectangle around them. For crates to push,
bridges that sag or anything else simulated, useCharacterBody2d from nacatamalon/physics2d gives the same
character in the 2D world, and changing between the two is changing this one line.
It is moved once every useUpdate of the scene is over, where the game set its speed, and before
hitboxes are compared and useLateUpdate runs. Slopes are measured under the middle of its feet,
and a block of any height on flat ground is a wall. A map can be moved and scaled, not turned.
Parameters
optionsTCharacterShape2dIts size, and how it falls.
Example
const Hero = () => {
createSprite({ key: 'hero', transform: { x: 40, y: 100 } });
const body = useTileBody2d({ width: 12, height: 24 });
const keys = useKeyboard();
useUpdate(() => {
const walk = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);
body.velocity.x = walk * 90;
if (keys.justPressed('x') && body.isOnGround) body.velocity.y = -300;
if (keys.justPressed('ArrowDown') && body.isOnOneWay && !body.isOnLadder) body.dropThrough();
// Onto a ladder with up in front of it, or with down standing on its top.
const up = keys.isDown('ArrowUp') && !body.isOnOneWay;
const down = keys.isDown('ArrowDown') && body.isOnOneWay;
if (body.isOnLadder && (up || down)) body.climbing = true;
if (body.climbing) body.velocity.y = keys.isDown('ArrowUp') ? -60 : keys.isDown('ArrowDown') ? 60 : 0;
});
};
View source · physics/character/use_tile_body_2d.ts:57#TCharacterBody2dtypenacatamalon
A character of a platformer, moved by the game and stopped by the map: by its walls, ledges and
slopes, and, made with useCharacterBody2d, by everything else in the simulation, which it can
push. useTileBody2d and useCharacterBody2d both give one, so a game can change which it uses
by changing one line.
Every field but velocity and climbing is read only, and each says what happened in the last
move, the one after the updates of the previous frame.
Properties
velocity{ x, y }Pixels per second, written by the game from a useUpdate: x walks, a negative y jumps, and
gravity pulls y down between moves. Standing on the ground or hitting a ceiling sets y back
to nothing; x is left as the game wrote it.
climbingbooleanOn a ladder, climbing: no gravity, ledges passed through, moved only by velocity. The game
sets it, when up is pressed on a ladder (isOnLadder) or down on its top; it goes back to false
by itself once the character is off the ladder, out of its top (where it then stands, on a top that
is a ledge) or its side.
isOnGroundbooleanStanding on something: a floor, a ledge, a slope, a crate.
isOnCeilingbooleanIts head hit something on the way up.
wallSide'left' | 'right' | nullPressed against a wall, and on which side.
isOnOneWaybooleanStanding on a ledge (oneWay), which dropThrough() falls through.
isOnLadderbooleanIn front of a ladder tile, or standing on top of one, which is when the game may set climbing:
up in front of it climbs it, down on its top climbs down it.
groundTTileDoc | undefinedThe tile underfoot, for what the game wrote on it (ground?.props?.ice), or undefined in the
air and on anything that is not a map.
damagenumberThe largest damage of the tiles it is touching, 0 for none. The game decides what it means.
dropThrough() => voidFalls through the ledge it is standing on. Nothing happens anywhere else.
setPosition(x: number, y: number) => voidPuts it somewhere without asking the world: spawning, respawning. It can put it inside a wall.
destroy() => voidStops moving the object and takes the character out of the simulation.
View source · physics/character/t_character_body_2d.ts:16#TCharacterShape2dtypenacatamalon
What a character is, whatever moves it: its size, where that sits on the object, and how it falls.
Properties
widthnumberThe box it collides with, in the object's own pixels: usually narrower than its picture, as
the old games did, so it fits through a gap one tile wide.
heightnumberoffsetoptional[number, number]Where the box's centre is from the object's position, in its own pixels. [0, 0] by default.
gravityoptionalnumberPixels per second squared, pulling down. 900 by default (the world's gravity, for a character
in one), which with step: 60 is a quarter of a pixel a frame, a classic platformer's.
maxFalloptionalnumberThe fastest it falls, in pixels per second. 420 by default: seven pixels a frame at step: 60.
View source · physics/character/t_character_body_2d.ts:81#TCollider2dtypenacatamalon
TCollider2d: { shape, width, height } | { shape, radius } | { shape, vertices }
The shape a flat body collides with, centred on where the object is.
Centred and not cornered, because that is where this engine puts a picture too: a sprite's
anchor is its middle unless somebody says otherwise, so a shape the same size as the art lines
up with it without anybody working out an offset. An object drawn from its corner (anchor at
zero, which is how a floor is usually written) is the case where the two differ, and there the
placement is the corner and the shape is still around it.
The set is small and closed on purpose. It is what any 2D physics engine has in common, not a
copy of one library's list: the document has to outlive whatever is simulating it, and a shape no
backend can build would be a field that does nothing.
View source · physics/types/t_physics.ts:34#TCollider3dtypenacatamalon
TCollider3d: { shape, size } | { shape, radius } | { shape, radius, height } | { shape, geometry } | { shape, geometry }
The shape a body in three dimensions collides with, around the object's origin unless it carries
an offset.
View source · physics/types/t_physics.ts:50#TPhysicsBodytypenacatamalon
TPhysicsBody: TPhysicsBody2d | TPhysicsBody3d | TRetroBody2d
Any kind of collider, told apart by _type: flat, in space, or retro (see TRetroBody2d).
Separate types and not one with a flag, because their shapes do not overlap (a circle is not a
sphere) and everything reading them would otherwise have to unwrap one discriminant inside another.
View source · physics/types/t_physics.ts:184#TPhysicsBody2dtypenacatamalon
TPhysicsBody2d: { _type, id, name, body, collider } & TPhysicsSurface
A flat collider on an object: what it is made of, and how it is driven.
Where it is is not here. The object owns that, by the standing rule that a component carries
no placement of its own, which is also why moving the object moves its collider.
Properties
_type'physics-body-2d'idstringnamestringbouncenumberBounciness: how much of the speed it arrived with it leaves with, 0 to 1.
It belongs to the pair and not to one body: an engine mixes the two colliders' values
(usually by averaging), so a ball asking for 0.8 landing on a floor left at 0 bounces at
0.4. Set both sides.
frictionnumberdensitynumberWeight comes from this and the shape's size, and is never set directly.
sensorbooleanNotices overlaps without settling them, so things pass straight through: a checkpoint, a
pickup, a place that hurts.
layernumberWhich layer this body is on, 0 to 15. In code it can be said by the name the game gave
it (physicsLayers); the record keeps the number.
One layer, and the restraint is deliberate: "what is this thing" has one answer in every game
that has ever needed layers, and the moment something is on two, a table of what hits what
stops being readable by eye. What varies is what it collides with.
collidesWithnumberA mask of the layers this body collides with: 1 << n per layer, so PHYSICS.ALL_LAYERS is
everything and (1 << 0) | (1 << 2) is layers 0 and 2.
It is mutual, and that is the rule that surprises people. Two bodies meet only if each
one's mask includes the other's layer, so a bullet that lists walls still passes through them
unless walls also list bullets. Both backends work that way, so the format says so instead of
papering over it: a one-sided rule would have to be faked on both sides and still would not
mean the same thing in each.
View source · physics/types/t_physics.ts:140#TPhysicsBody2dOptionstypenacatamalon
TPhysicsBody2dOptions: { id, name, body, collider } & Partial<Omit<TPhysicsSurface, 'layer' | 'collidesWith'>> & TPhysicsLayerOptions
What a flat body is made from: how it moves, its shape, and how it feels to touch. id and
name are only for keeping the identity a scene document gave it.
Properties
idoptionalstringnameoptionalstringlayeroptionalTPhysicsLayercollidesWithoptionalnumber | typeOperator
View source · hooks/physics/use_physics_body.ts:22#TPhysicsBody3dtypenacatamalon
TPhysicsBody3d: { _type, id, name, body, collider, offset } & TPhysicsSurface
A collider in three dimensions. See TPhysicsBody2d for why the placement is not here.
Properties
_type'physics-body-3d'idstringnamestringoffset[number, number, number]Where the shape sits inside the object, before its scale.
This does not contradict the rule above: the object still owns where the object is, and
this says where the shape sits within it, which is a different question.
It exists because of models. An imported one almost always puts its origin where the thing
stands, at a character's feet, while a collider is centred on that origin, so fitting a
body to such a model buries half of it in the floor.
bouncenumberBounciness: how much of the speed it arrived with it leaves with, 0 to 1.
It belongs to the pair and not to one body: an engine mixes the two colliders' values
(usually by averaging), so a ball asking for 0.8 landing on a floor left at 0 bounces at
0.4. Set both sides.
frictionnumberdensitynumberWeight comes from this and the shape's size, and is never set directly.
sensorbooleanNotices overlaps without settling them, so things pass straight through: a checkpoint, a
pickup, a place that hurts.
layernumberWhich layer this body is on, 0 to 15. In code it can be said by the name the game gave
it (physicsLayers); the record keeps the number.
One layer, and the restraint is deliberate: "what is this thing" has one answer in every game
that has ever needed layers, and the moment something is on two, a table of what hits what
stops being readable by eye. What varies is what it collides with.
collidesWithnumberA mask of the layers this body collides with: 1 << n per layer, so PHYSICS.ALL_LAYERS is
everything and (1 << 0) | (1 << 2) is layers 0 and 2.
It is mutual, and that is the rule that surprises people. Two bodies meet only if each
one's mask includes the other's layer, so a bullet that lists walls still passes through them
unless walls also list bullets. Both backends work that way, so the format says so instead of
papering over it: a one-sided rule would have to be faked on both sides and still would not
mean the same thing in each.
View source · physics/types/t_physics.ts:155#TPhysicsBody3dOptionstypenacatamalon
TPhysicsBody3dOptions: { id, name, body, collider, offset } & Partial<Omit<TPhysicsSurface, 'layer' | 'collidesWith'>> & TPhysicsLayerOptions
The same for a body in space.
Properties
idoptionalstringnameoptionalstringoffsetoptional[number, number, number]layeroptionalTPhysicsLayercollidesWithoptionalnumber | typeOperator
View source · hooks/physics/use_physics_body.ts:36#TPhysicsBodyTypetypenacatamalon
TPhysicsBodyType: 'static' | 'dynamic' | 'kinematic'
How a body is driven, and what it lets happen to it.
'static' never moves and nothing can push it: walls, the ground, the level. 'dynamic' is
driven by gravity, forces and contacts, and is what "a physics object" usually means.
'kinematic' is driven by you and pushes others without being pushed back: a moving platform, a
lift, a boss on rails.
View source · physics/types/t_physics.ts:15#TPhysicsLayertypenacatamalon
TPhysicsLayer: number | string
A collision layer, by its number (0 to 15) or by the name the game gave it in
physicsLayers ('enemy').
View source · physics/layer_names.ts:14#TPhysicsLayerOptionstypenacatamalon
How a body says what layer it is on and what it collides with: by number, as the format keeps
them, or by the names the game gave its layers (physicsLayers in createGame or the project).
collidesWith is a mask (1 << n) or a list of layers: ['world', 'enemy'].
Properties
layeroptionalTPhysicsLayercollidesWithoptionalnumber | typeOperator
View source · physics/layer_names.ts:25#TPhysicsSurfacetypenacatamalon
What a collider is made of: how a contact settles, and whether it settles at all.
Every field is required, and that is the point. This is the written-down truth of a scene, and
an absent value would mean "whatever the adapter does", which would make the meaning of a document
depend on who reads it. A scene that behaves differently under a different backend is exactly the
coupling this format exists to prevent.
Properties
bouncenumberBounciness: how much of the speed it arrived with it leaves with, 0 to 1.
It belongs to the pair and not to one body: an engine mixes the two colliders' values
(usually by averaging), so a ball asking for 0.8 landing on a floor left at 0 bounces at
0.4. Set both sides.
frictionnumberdensitynumberWeight comes from this and the shape's size, and is never set directly.
sensorbooleanNotices overlaps without settling them, so things pass straight through: a checkpoint, a
pickup, a place that hurts.
layernumberWhich layer this body is on, 0 to 15. In code it can be said by the name the game gave
it (physicsLayers); the record keeps the number.
One layer, and the restraint is deliberate: "what is this thing" has one answer in every game
that has ever needed layers, and the moment something is on two, a table of what hits what
stops being readable by eye. What varies is what it collides with.
collidesWithnumberA mask of the layers this body collides with: 1 << n per layer, so PHYSICS.ALL_LAYERS is
everything and (1 << 0) | (1 << 2) is layers 0 and 2.
It is mutual, and that is the rule that surprises people. Two bodies meet only if each
one's mask includes the other's layer, so a bullet that lists walls still passes through them
unless walls also list bullets. Both backends work that way, so the format says so instead of
papering over it: a one-sided rule would have to be faked on both sides and still would not
mean the same thing in each.
View source · physics/types/t_physics.ts:89#TPhysicsWorldtypenacatamalon
TPhysicsWorld: TPhysicsWorld2d | TPhysicsWorld3d | TRetroWorld2d
Any simulation's settings: flat, in space, or retro. A scene has at most one, and it lives on the scene's root:
gravity is a property of the scene and not of anything in it (a scene seen from above has none, a
platformer does), and the root is an object like any other, so it needs no new home.
View source · physics/types/t_physics.ts:233#TPhysicsWorld2dtypenacatamalon
The flat simulation's settings for one scene.
gravity is in pixels per second squared with +y pointing DOWN, because that is the way a
sprite's y axis grows and the simulation writes straight onto a placement. So earth-ish gravity is
about 900, positive: the opposite sign from three dimensions. The disagreement is deliberate,
because turning 2D into metres would put a pixels-per-metre factor into every flat game and every
push, and buy a tidiness no author benefits from, since no scene mixes the two.
Properties
_type'physics-world-2d'idstringIts own id, like every other component. A world has no name (neither does a camera), and it
still has to be addressable: a tool selects and removes it by id.
gravity{ x, y }
View source · physics/types/t_physics.ts:199#TPhysicsWorld3dtypenacatamalon
The simulation's settings in three dimensions. gravity is in metres per second squared with
+y UP, so earth is { x: 0, y: -9.81, z: 0 }. See TPhysicsWorld2d for why the two
disagree on purpose.
Properties
_type'physics-world-3d'idstringgravity{ x, y, z }
View source · physics/types/t_physics.ts:218#TRetroBody2dtypenacatamalon
A retro collider on an object: what it is, how it moves, and what it is made of.
The retro half of physics. Bodies that never turn, moved in pixels a fixed step at a time and
stopped against each other axis by axis, the way the old games did: nothing to load, the same
result on every machine. It lives in the same place on the object as a collider of the full
simulation (physics), because an object has one body, whichever half moves it. It is installed
apart (installRetroPhysics2d() from nacatamalon/retro-physics2d) and the two can run in one game:
each moves its own bodies, and the two halves do not collide with each other.
Every field is required, as on the full simulation's surface: this is the written-down truth of a
scene, and an absent value would mean "whatever the reader does".
Where it is is not here: the object owns that, as it does for every component.
Properties
_type'retro-body-2d'idstringnamestringbodyTPhysicsBodyType'static' never moves; 'dynamic' moves by its speed, falls and is pushed; 'kinematic'
moves by its speed, pushes and is never pushed: a lift, a platform on rails.
colliderTRetroCollider2dWhat it collides with, read every step: give it a new one at any moment (a hero a mushroom
makes big, record.collider = { shape: 'rect', width: 14, height: 28 }), or scale the object.
A dynamic body standing when its size changes keeps its feet where they were, so it grows up
from the floor and shrinks down to it, and it comes out of any solid tile it grew into.
enabledbooleanWhether it is simulated: off, it neither moves nor stops anything, and touches nothing, until it
is on again. The object stays where it is, and the game can move it.
bounceTRetroBounceHow much of its speed it keeps when something stops it, 0 to 1, for every way or for each
axis. The body's own, and not mixed with what it hit: a ball at 1 comes off every wall as fast
as it arrived.
dragnumberPixels per second squared slowing each axis towards stopping, 0 for none: the slide of
a character who lets go of the pad.
maxSpeedTRetroMaxSpeed | nullThe fastest it goes, whole or on each axis, or null for no limit.
gravityScalenumberHow much of the world's gravity pulls it: 1 all of it, 0 none (a bullet, a scene seen
from above), -1 upwards.
massnumberHow a push between two dynamic bodies is shared: the lighter one gives way more. Set directly,
because a retro body has no material to weigh.
pushablebooleanWhether other dynamic bodies can push it. false is a body that still falls, moves and is
stopped by walls, but stands like a wall to the others: a player enemies cannot shove. What is
driven ('kinematic') still pushes it.
solidSidesTRetroSidesWhich of its sides stop what comes against them. All four by default; only up makes a
platform to jump through from below and stand on from above.
boundsTRetroBoundsWhat it does at the edges of its world (bounds on the world): pass, stop, or wrap.
carriesnumberHow much of its own movement it gives to what stands on it, 0 to 1: 1 carries a rider all
the way, 0 slides out from under it, like ice on rails.
sensorbooleanNotices overlaps without stopping anything: a checkpoint, a pickup, a place that hurts.
layernumberThe layer it is on and a mask of the layers it collides with, both as on the full simulation's
surface (see TPhysicsSurface), and mutual in the same way.
collidesWithnumber
View source · physics/types/t_retro_physics.ts:81#TRetroBody2dOptionstypenacatamalon
TRetroBody2dOptions: { id, name, body, collider } & Partial<Omit<TRetroBody2d, '_type' | 'id' | 'name' | 'body' | 'collider' | 'layer' | 'collidesWith' | 'solidSides'>> & { solidSides } & TPhysicsLayerOptions
What a retro body is made from: how it moves, its shape, and how it behaves when stopped. id
and name are only for keeping the identity a scene document gave it.
Properties
idoptionalstringnameoptionalstringsolidSidesoptionalPartial<indexedAccess>layeroptionalTPhysicsLayercollidesWithoptionalnumber | typeOperator
View source · hooks/physics/use_retro_body.ts:21#TRetroBouncetypenacatamalon
TRetroBounce: number | { x, y }
How much of its speed a retro body keeps when something stops it, 0 to 1: one number for every
way, or one for each axis (a ball that keeps all its speed off the walls and half off the floor).
View source · physics/types/t_retro_physics.ts:39#TRetroBoundstypenacatamalon
TRetroBounds: 'pass' | 'stop' | 'wrap'
What a retro body does at the edges of its world: goes on past them ('pass'), is stopped by them
like by a wall ('stop'), or comes back in by the opposite edge ('wrap'), as the ships and rocks
of the old space games did.
View source · physics/types/t_retro_physics.ts:60#TRetroCollider2dtypenacatamalon
TRetroCollider2d: { shape, width, height } | { shape, radius }
The shape a retro body collides with, centred on where the object is, like every flat collider
of this engine (see TCollider2d for why centred).
Two shapes and no turning, and that is the point of the retro half: a box that stays square to the
screen and a ball are what the games of the era collided with, and two of each meet with a few
comparisons a frame and the same answer on every machine. The object can still be drawn turned;
what it collides with does not turn with it.
View source · physics/types/t_retro_physics.ts:16#TRetroMaxSpeedtypenacatamalon
TRetroMaxSpeed: number | { x, y }
How fast a retro body may go, in pixels per second: one number for its whole speed, whichever way
it goes (a ship seen from above), or one for each axis on its own (a platformer's character runs
at one speed and falls at another).
View source · physics/types/t_retro_physics.ts:29#TRetroSidestypenacatamalon
Which sides of a retro body stop what comes against them. A platform with only up is one you
jump through from below and stand on from above.
Properties
upbooleandownbooleanleftbooleanrightboolean
View source · physics/types/t_retro_physics.ts:49#TRetroWorld2dtypenacatamalon
The retro simulation's settings for one scene: how hard things fall, in pixels per second squared
with +y down, like the full flat simulation's. Lives on the scene's root.
Properties
_type'retro-world-2d'idstringgravity{ x, y }bounds{ x, y, width, height } | nullThe world's edges, for bodies that stop or wrap at them, in the world's pixels; null for the
game's screen, from its top left corner.
timeScalenumberHow fast its time goes: 1 as the game's, 0.5 in slow motion, 0 paused. Read every frame,
so changing it on the world useRetroWorld2d gave back slows the world from then on.
View source · physics/types/t_retro_physics.ts:167nacatamalon/physics2d
#getPhysicsBody2dfunctionnacatamalon/physics2d
getPhysicsBody2d(object: TGameObject) => TPhysicsBodyHandle2d | null
The body of object as the simulation moves it, or null if it has none.
usePhysicsBody2d says what an object is made of, and this gives the body it became: the one to
push, stop, spin and listen to. It is the same pair as usePhysicsWorld2d and getPhysicsWorld2d.
It finds the body by the object alone, wherever and whenever it is asked: while the scene is
built, from a script on a box of a scene file, or in any frame after.
Each object has one handle, so a listener connected through one call and one connected
through another hear the same contacts.
null is an ordinary answer and the game must allow for it: in the editor, while a scene is being
built rather than played, nothing simulates; an object with no collider has no body; and a script
that runs before its own collider is declared asks too early. Asked in useUpdate, it is found
as soon as there is one.
Parameters
objectTGameObjectThe object whose body is wanted: self in a script, useSelf() while one is
built, or any object found or spawned.
Example
import { createScene, createSprite, useSpawn, usePhysicsBody2d, usePhysicsWorld2d, useSelf, useUpdate } from 'nacatamalon';
import { getPhysicsBody2d } from 'nacatamalon/physics2d';
const Platform = () => {
createSprite({ tint: '#7a5a3a', width: 64, height: 12, transform: { x: 100, y: 120 } });
usePhysicsBody2d({ body: 'kinematic', collider: { shape: 'rect', width: 64, height: 12 } });
const self = useSelf();
useUpdate((_delta, time) => {
// Back and forth, at a speed the simulation keeps until it is told another.
getPhysicsBody2d(self)?.setLinearVelocity(Math.sin(time) * 80, 0);
});
};
const Level = () => {
usePhysicsWorld2d();
useSpawn(Platform)();
return createScene();
};
View source · physics/box2d/provider.ts:118#getPhysicsWorld2dfunctionnacatamalon/physics2d
getPhysicsWorld2d() => TPhysicsWorldHandle2d | null
The 2D physics world the running scene's document built, or null if it has none.
The seam between authored data and authored behaviour, and the 2D twin of the 3D adapter's
accessor of the same name. A collider is data: the document declares it and this provider
simulates it, no code on either side. Steering is not: a script attached to a box has no way
to name the world the scene root declared, because that world never passed through the
document. Without this the only reachable world is one the script opens itself, which is a
second world with its own gravity and its own bodies, colliding with nothing in the scene.
To move or listen to one object's body, getPhysicsBody2d(object) is the way: it needs no world.
null is the ordinary answer, not an error, and scripts must handle it: the editor's edit
viewport deserializes the same document with no provider registered (see play.ts), so a
script runs there with no world and must simply do nothing. That is what keeps the workspace
from simulating while you author in it.
registerScript('grapple', (self) => {
const world = getPhysicsWorld2d();
if (!world) return; // editing, not playing
// A rope to the ceiling, thrown at any moment: something only the world itself is asked for.
usePointer().onDown(() => {
world.addJoint(self, null, { type: 'rope', atB: { x: 160, y: 0 } });
});
});
Call it during scene init, which is when a script runs, so this is the ordinary case. Outside
init there is no active game to compare against and the answer is always null.
View source · physics/box2d/provider.ts:67#installPhysics2dfunctionnacatamalon/physics2d
installPhysics2d() => void
Installs this as what simulates the flat half of a scene's physics. The one line a game
writes, and the only one: everything else about physics is the engine's vocabulary, so a scene
says what it is made of and this makes it move.
It is a call and not something that happens on import, for three separate reasons, any one of
which would be enough. The engine declares itself free of side effects, so a bundler is allowed
to drop an import nothing is used from, and a game that worked in development would sit still
once built. A tool must be able to open a scene and NOT simulate it, which is what lets you build
a level in a workspace that holds still. And a game may install the solid half as well, which it
does the same way, by saying so.
import { installPhysics2d } from 'nacatamalon/physics2d';
installPhysics2d();
Installing twice does nothing the second time.
View source · physics/box2d/provider.ts:256#loadPhysics2dfunctionnacatamalon/physics2d
loadPhysics2d() => Promise<void>
Loads what simulates the 2D physics, ahead of the first scene that needs it: once a page, however
often it is called. A world loads it on its own the first time, and its bodies wait for it, so this
is only for a game that would rather pay that wait on a loading screen than in its first level.
Example
import { installPhysics2d, loadPhysics2d } from 'nacatamalon/physics2d';
installPhysics2d();
await loadPhysics2d();
View source · physics/box2d/load_box2d.ts:186#physics2dProvidervariablenacatamalon/physics2d
physics2dProvider: TPhysicsProvider
Moves the physics a scene declares, on Box2D.
This is the adapter's half of the split: the engine keeps colliders, writes them down and reads
them back while deliberately being unable to move them, and registering this is what makes a
scene actually fall. Nothing here is needed to author physics: a tool opens, edits and saves
a scene with none of it installed.
It is handed everything a scene declares, whether that came from a file or from a line somebody
typed, because the engine records it and then asks. There is nothing here that only one of those
two paths goes through.
import { registerPhysicsProvider } from 'nacatamalon/extend';
import { physics2dProvider } from 'nacatamalon/physics2d';
registerPhysicsProvider(physics2dProvider);
Properties
createWorld(world: TPhysicsWorld) => voidCalled once for the world a scene declares, and always before any body of that scene: the
world lives on the scene's root, and a root is built before what is under it.
createBody(box: TBox, body: TPhysicsBody) => voidCalled for each object carrying a collider. box is the object that owns it: where it starts
and where the simulation writes back to.
watchContactsoptional(box: TBox, told: (other: TBox, started: boolean) => void) => booleanTells told from now on whenever the body of box starts or stops touching another, with the
other's box: what collisions asked by component or by tag count. Answers whether it is the one
simulating that body, so the engine knows to ask no other. Optional: a provider without it
only leaves physics out of those collisions.
hasBodyoptional(box: TBox) => boolean | undefinedWhether box still has a body here: true or false when this provider simulates it, and
undefined when it is not this provider's. A body taken away while its object stays touches
nothing any more. Optional, like watchContacts.
createCharacter2doptional(box: TBox, shape: TCharacterShape2d) => TCharacterBody2d | undefinedA platformer's character for useTileBody2d on box, when this provider moves the scene the
object is in and has a character of its own, which then walks among its bodies as well as on
the maps. undefined leaves it to the character that walks on the maps alone. Optional.
drawDebugoptional(scene: TBox, draw: TDebugDraw) => voidDraws what this provider moves in scene for the debug mode (useGame().setDebugEnabled),
once a frame while it is on. The engine already draws the colliders of the full simulation
from what each object keeps, the hitboxes and the maps' tiles; this is for what only the
provider knows. Optional.
View source · physics/box2d/provider.ts:172#useCharacterBody2dfunctionhooknacatamalon/physics2d
useCharacterBody2d(options: TCharacterOptions2d) => TCharacterBody2d
Makes this object a platformer's character: the game says how fast it goes, and the world stops it
at the map's walls, holds it on ledges and slopes, and lets it push what the simulation moves.
Moved by the game, not by physics. It does not slide, bounce or keep its speed: it goes at the
speed the game writes into velocity, every frame, and stops dead when the game writes nothing.
That is how the old platformers felt, and it still lives in the simulation, so a crate is pushed by
it, a bridge sags under it, and something falling lands on its head.
It is moved once every useUpdate of the scene is over, where the game set its speed, so what the
game decides this frame is seen this frame, and before hitboxes are compared and useLateUpdate
runs, so a camera follows it where it ended up.
What it reads from the map's tiles: walls (solid), ledges (oneWay, landed on from above,
dropThrough() to fall through), slopes (slope), ladders (isOnLadder, then the game sets
climbing), belts and currents (push, which carry it), harm (damage, which it reports and
never applies) and the tile underfoot (ground, for whatever the game wrote in its props).
Needs the scene's 2D world (usePhysicsWorld2d) and installPhysics2d(). Where nothing simulates,
as in a tool showing the scene, it is a character that never moves.
Parameters
optionsTCharacterOptions2dIts size, and how it falls, climbs and pushes.
Example
import { createSprite, useKeyboard, useUpdate } from 'nacatamalon';
import { useCharacterBody2d } from 'nacatamalon/physics2d';
const Hero = () => {
createSprite({ key: 'hero', transform: { x: 40, y: 100 } });
const body = useCharacterBody2d({ width: 12, height: 24 });
const keys = useKeyboard();
useUpdate(() => {
const walk = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);
body.velocity.x = walk * 90;
if (keys.justPressed('x') && body.isOnGround) body.velocity.y = -300;
if (keys.justPressed('ArrowDown') && body.isOnOneWay && !body.isOnLadder) body.dropThrough();
// Onto a ladder with up in front of it, or with down standing on its top.
const up = keys.isDown('ArrowUp') && !body.isOnOneWay;
const down = keys.isDown('ArrowDown') && body.isOnOneWay;
if (body.isOnLadder && (up || down)) body.climbing = true;
if (body.climbing) body.velocity.y = keys.isDown('ArrowUp') ? -60 : keys.isDown('ArrowDown') ? 60 : 0;
});
};
View source · physics/box2d/use_character_body_2d.ts:80#useJoint2dfunctionhooknacatamalon/physics2d
useJoint2d(a: TGameObject, b: TGameObject | null, joint: TJoint2d) => TJointHandle2d
Joins two objects' bodies, or one to a point of the world when b is null: the planks of a
bridge, a pendulum on its nail, a platform on a spring, a door on its hinge.
Both objects need a body (usePhysicsBody2d) in the scene's 2D world. Points are given where the
scene lays things out, in the world, so a bridge's planks are pinned where they meet. The two
joined bodies do not collide with each other unless the joint says collide: true.
A bridge wants three things to hang still: a little slack (planks a touch longer than the gap, so it
sags), a little friction in its hinges, and its ends pinned a pixel or two off the banks, since a
plank flush against a wall rubs on it and never settles.
The joint goes with whichever of its objects is destroyed first, and earlier with destroy().
Call it while the scene is built; to join things later (a hook thrown mid-jump), keep the world
from getPhysicsWorld2d() and call its addJoint. Where nothing simulates, it joins nothing.
Parameters
bTGameObject | nullThe other, or null for a fixed point of the world.
jointTJoint2dHow they are joined: see TJoint2d.
Example
import { createScene, createSprite, usePhysicsBody2d, usePhysicsWorld2d, useSpawn } from 'nacatamalon';
import { useJoint2d } from 'nacatamalon/physics2d';
import type { TGameObject, TSceneFn } from 'nacatamalon';
// A bridge of eight planks between two ledges, pinned to the world at both ends.
const Plank = (x: number) => {
createSprite({ key: 'plank', transform: { x, y: 120 } });
usePhysicsBody2d({ body: 'dynamic', collider: { shape: 'rect', width: 16, height: 4 } });
};
export const River: TSceneFn = () => {
usePhysicsWorld2d();
const spawnPlank = useSpawn(Plank);
const planks: TGameObject[] = [];
for (let i = 0; i < 8; i++) planks.push(spawnPlank(72 + i * 16));
useJoint2d(planks[0], null, { type: 'hinge', at: { x: 64, y: 120 } });
for (let i = 1; i < planks.length; i++) {
useJoint2d(planks[i - 1], planks[i], { type: 'hinge', at: { x: 64 + i * 16, y: 120 } });
}
useJoint2d(planks[7], null, { type: 'hinge', at: { x: 64 + 8 * 16, y: 120 } });
return createScene();
};
View source · physics/box2d/use_joint_2d.ts:61#useSoftBody2dfunctionhooknacatamalon/physics2d
useSoftBody2d(options: TSoftBodyOptions2d) => TSoftBody2d
Makes the object being built a soft body in the scene's 2D world: something that squashes, wobbles
and rolls rather than keeping its shape. A blob of goo, a jelly, a ball of dough, a rope.
It is a ring of corners held to one another, and to the area they enclose, by springs. It falls,
lands on the map and on the other bodies, rolls down slopes and squashes against walls. The object
is kept at its middle, and outline says where its corners are. Give it a polygon made with
createPolygon and the corners of that are moved to the body's every frame, the picture stretching
with them.
A soft body rolls without turning its object: its turn is in where its corners are.
Parameters
optionsTSoftBodyOptions2dThe shape it starts as and what it is made of: see TSoftBodyOptions2d.
Example
import { createGame, createPolygon, createScene, useKeyboard, usePhysicsWorld2d, useSpawn, useTransform, useUpdate } from 'nacatamalon';
import { installPhysics2d, useSoftBody2d } from 'nacatamalon/physics2d';
installPhysics2d();
// A green blob that hops with space.
const Blob = () => {
useTransform({ x: 160, y: 40 });
const ring = Array.from({ length: 16 }, (_, i) => ({ x: Math.cos(i / 16 * Math.PI * 2) * 20, y: Math.sin(i / 16 * Math.PI * 2) * 20 }));
const polygon = createPolygon({ points: ring, tint: '#5bd75b' });
const blob = useSoftBody2d({ shape: 'disk', radius: 20, polygon });
const keys = useKeyboard();
useUpdate(() => {
if (keys.justPressed(' ')) blob.kick(0, -300);
});
};
const Level = () => {
usePhysicsWorld2d();
useSpawn(Blob)();
return createScene();
};
createGame('#app', { width: 320, height: 180 })({ Level });
View source · physics/box2d/use_soft_body_2d.ts:66#TCharacterOptions2dtypenacatamalon/physics2d
TCharacterOptions2d: TCharacterShape2d & { maxSlope, pushes, mass, layer, collidesWith }
What a character in the simulation is: its size and how it falls, and how it climbs and pushes.
Properties
maxSlopeoptionalnumberThe steepest slope it walks up, in radians. About 50° by default; steeper ones it slides down.
pushesoptionalbooleanWhether walking into something the simulation moves pushes it. true by default.
massoptionalnumberHow heavy it is: what it weighs on a bridge or a crate it stands on, and how heavy a thing it can
push at full pace. Left out, its size at the density of a crate (width times height).
layeroptionalnumberIts collision layer and what it collides with, as any body's.
collidesWithoptionalnumberwidthnumberThe box it collides with, in the object's own pixels: usually narrower than its picture, as
the old games did, so it fits through a gap one tile wide.
heightnumberoffsetoptional[number, number]Where the box's centre is from the object's position, in its own pixels. [0, 0] by default.
gravityoptionalnumberPixels per second squared, pulling down. 900 by default (the world's gravity, for a character
in one), which with step: 60 is a quarter of a pixel a frame, a classic platformer's.
maxFalloptionalnumberThe fastest it falls, in pixels per second. 420 by default: seven pixels a frame at step: 60.
View source · physics/box2d/character_body_2d.ts:17#TColliderSurface2dtypenacatamalon/physics2d
The non-geometric properties of a collider: how it responds to a contact, and whether it
resolves the contact at all.
Properties
bounceoptionalnumberHow much approach speed survives as separation speed, 0..1.
Careful: a bounce belongs to the pair, not to this body. The two colliders' values are
averaged, so a ball asking for 0.8 landing on a floor that never set one (and is therefore
0) bounces at 0.4. Set both sides. Friction is averaged the same way.
frictionoptionalnumberdensityoptionalnumbersensoroptionalbooleanMake this a sensor: it detects overlaps but never resolves them, so things pass
straight through. This is the trigger volume (a checkpoint, a pickup, a damage zone)
and it is the case onEnter/onExit exist for.
layeroptionalnumberWhich collision layer this body is on (0..15) and which layers it collides with (a
bitmask): see the engine's TPhysicsSurface. The relationship is mutual: a bullet listing
"walls" passes straight through unless walls also list "bullets". Omitted means layer 0
against everything, which is how every body behaved before layers existed.
collidesWithoptionalnumber
View source · physics/box2d/types.ts:19#TJoint2dtypenacatamalon/physics2d
TJoint2d: { type, at, limits, motor, friction } | { type, length, atA, atB } | { type, length, frequency, damping, atA, atB } | { type, axis, at, limits, motor, friction } | { type } & { collide }
How two bodies are joined, or one body to a point of the world.
Every point is a point of the world where the scene lays the bodies out, not one measured on
either body: a bridge's planks are pinned where they meet, a pendulum where its nail is.
'hinge': pinned together at at, each free to turn about it: the planks of a bridge, a door, a
pendulum, a windmill with a motor. limits bounds the turn, in radians either side of where
it started.
'rope': never further apart than length (their distance at the start, by default), and free
to come closer: a hanging lamp, a grappling hook. Tied at atA and atB, their centres by default.
'spring': pulled back to length apart: a platform that bounces, a car's suspension. Said as
how many times a second it bounces, frequency (2 by default), and how soon it settles,
damping (0 bounces for ever, 1 settles without a bounce; 0.3 by default), so a heavy crate
and a light one bounce alike.
'slider': free to move along axis only, through at (b's centre by default), without
turning: a platform on a rail, a piston. limits bounds the travel, in pixels from where it
started.
'weld': held as they are now, as one: pieces that move together and still collide apart.
A hinge or a slider with friction slows down: its turning (or sliding) loses that much of itself
a second, whatever the bodies weigh, so it settles rather than swinging or rolling on for ever. 2
calms a swing in a few seconds, 5 in about one. Nothing else in the world slows a joint down, so
without it a bridge sways as long as the game runs.
collide says whether the two bodies collide with each other; false by default, since joined
pieces usually touch, and two planks of a bridge pushing each other apart is not a bridge.
Properties
collideoptionalboolean
View source · physics/box2d/t_joint_2d.ts:52#TJointHandle2dtypenacatamalon/physics2d
A joint once made: what lets it go before its bodies do.
Properties
destroy() => voidLets the two bodies go: a rope cut, a hook let go of, a bridge's plank snapped off. A joint
also goes by itself when either of its objects is destroyed.
View source · physics/box2d/t_joint_2d.ts:67#TPhysicsBodyHandle2dtypenacatamalon/physics2d
Handle to a physics body registered in the world.
Properties
onEnteronExitapplyImpulse(x: number, y: number) => voidApply an instantaneous impulse (momentum change) at the body's center.
applyForce(x: number, y: number) => voidPushes it steadily for this frame: ask every frame for as long as it should push (a fan, a
thruster, wind), and it stops when the game stops asking. Several calls in one frame add up.
For one shove all at once, applyImpulse.
setLinearVelocity(vx: number, vy: number) => voidSet the linear velocity directly.
setAngularVelocity(w: number) => voidSet the angular velocity (rotation speed).
setLayers(layer: TPhysicsLayer, collidesWith?: number | typeOperator) => voidMoves the body to another collision layer, and changes what it collides with, while the game
runs: a player who passes through enemies for a moment after being hit, a ball that stops
meeting the pegs once it has bounced. The same two values the body was created with (see the
engine's TPhysicsSurface), and the same mutual rule: two bodies meet only if each one's mask
includes the other's layer.
By number or by the names the game gave its layers (physicsLayers): setLayers('ghost', ['world']). collidesWith left out keeps the mask the body already had. The object's physics record is
updated too, so a scene saved afterwards keeps the layers it is simulating with.
destroy() => voidTakes the body out of the simulation and leaves the object where it is, still drawn and
still running its code: a coin that stops colliding while it plays its pick-up animation.
Destroying the object does this on its own. Safe to call twice, and a push through this handle
afterwards does nothing.
View source · physics/box2d/types.ts:119#TPhysicsWorldHandle2dtypenacatamalon/physics2d
The physics world interface returned by usePhysicsWorld.
Properties
addCircle(box: TGameObject, options: { type } & TColliderSurface2d & { radius }) => TPhysicsBodyHandle2dRegister a circular rigid body on an object.
addRect(box: TGameObject, options: { type } & TColliderSurface2d & { width, height }) => TPhysicsBodyHandle2dRegister a rectangular rigid body on an object.
addPolygon(box: TGameObject, options: { type } & TColliderSurface2d & { vertices }) => TPhysicsBodyHandle2dRegister a polygonal rigid body on an object.
addCharacter(box: TGameObject, options: TCharacterOptions2d) => TCharacterBody2dMakes box a platformer's character in this world: what useCharacterBody2d does for the
object being built.
addSoftBody(box: TGameObject, options: TSoftBodyOptions2d) => TSoftBody2dMakes box a soft body in this world: what useSoftBody2d does for the object being built.
addJoint(a: TGameObject, b: TGameObject | null, joint: TJoint2d) => TJointHandle2dJoins two objects' bodies, or one to a point of the world when b is null, at any moment:
a hook thrown in the middle of a jump. useJoint2d does it while the scene is built. The
joint is made as soon as both bodies are in the world, and let go of when either object is.
View source · physics/box2d/types.ts:199#TPhysicsWorldOptions2dtypenacatamalon/physics2d
World initialization options.
Properties
gravityoptional{ x, y }
View source · physics/box2d/types.ts:105#TSoftBody2dtypenacatamalon/physics2d
A soft body in the scene's 2D world, as useSoftBody2d gives it: where its corners are, and ways to
move it.
Properties
outlineReadonlyArray<{ x, y }>Where each corner is now, measured from the object's place, which the body keeps at its middle.
Empty until the world has started.
velocity{ x, y }How fast it is going as a whole, in pixels per second.
push(x: number, y: number) => voidPushes every corner this frame, in pixels per second each second whatever it weighs, as gravity
does: asked every frame, a wind or a slope that leans; asked once, almost nothing.
kick(x: number, y: number) => voidAdds to its speed at once, in pixels per second: a hop, a blow.
destroy() => voidTakes it out of the world. Destroying its object does it too.
View source · physics/box2d/t_soft_body_2d.ts:79#TSoftBodyOptions2dtypenacatamalon/physics2d
TSoftBodyOptions2d: TSoftBodyShape2d & { softness, damping, keepShape, mass, friction, bounce, pinned, polygon }
What a soft body is made of.
Properties
softnessoptionalnumberHow quickly it springs back into shape, in times a second: 5 by default, a jelly. Lower is
floppier (2 sags), higher is firmer (30 is a rubber ball).
dampingoptionalnumberHow soon its wobbling dies away: 1 by default, settling without bouncing back and forth;
0.2 wobbles for a while.
keepShapeoptionalbooleanHolds on to the shape it started as, and not only to its area and its sides, so it squashes
and comes back. true by default for a closed body: a ring held only by its sides and its area
gives way under a weight, and one blob landing on another can fold it inside out. false lets
it slump into whatever it fell on, like goo. A rope has no shape to keep.
massoptionalnumberHow much it weighs in all, spread over its corners. 1 by default.
frictionoptionalnumberHow much it grips what it touches: 0.5 by default, 0 slides like ice, 1 rolls rather than
slides.
bounceoptionalnumberHow much it bounces off what it hits: 0 by default.
pinnedoptionalnumber[]Corners held where they start: the ends of a rope, the corner of a flag on its pole. Counted
from 0, as in outline.
polygonoptionalTPolygonThe shape that draws it: its corners are moved to the body's every frame, its picture stretching
with them. Made in the same object, with as many corners ('disk' and 'rope' have corners,
16 and 12 by default).
View source · physics/box2d/t_soft_body_2d.ts:27#TSoftBodyShape2dtypenacatamalon/physics2d
TSoftBodyShape2d: { shape, radius, corners } | { shape, points } | { shape, to, corners }
The shape a soft body starts as, measured from its object's place.
'disk': a ring of corners round a circle, holding its area: a blob, a jelly, a ball of goo.
'polygon': a closed outline of the corners given, holding its area: any blob that is not round.
'rope': a line of corners from the object's place to to, which stretches and folds: a rope,
a vine, a tail. It holds no area.
View source · physics/box2d/t_soft_body_2d.ts:15nacatamalon/physics3d
#DEFAULT_RAY_DISTANCEvariablenacatamalon/physics3d
DEFAULT_RAY_DISTANCE: 1000
How far a ray reaches when nothing says otherwise.
Finite rather than infinite because the backend takes a translation vector, not a direction:
there is no "infinity" to hand it. A kilometre is far beyond any level this engine's retro
scope builds, so it reads as unlimited while staying a number the solver can use.
View source · physics/box3d/types.ts:257#getPhysicsBody3dfunctionnacatamalon/physics3d
getPhysicsBody3d(object: TGameObject) => TPhysicsBodyHandle3d | null
The body of object as the simulation moves it, or null if it has none.
usePhysicsBody3d says what an object is made of, and this gives the body it became: the one to
push, stop, spin and listen to. It is the same pair as usePhysicsWorld3d and getPhysicsWorld3d.
It finds the body by the object alone, wherever and whenever it is asked: while the scene is
built, from a script on a box of a scene file, or in any frame after.
Each object has one handle, so a listener connected through one call and one connected
through another hear the same contacts. A character's object gives its own collider if it has
one, never the capsule that moves it: that is useCharacterBody3d's.
null is an ordinary answer and the game must allow for it: in the editor, while a scene is being
built rather than played, nothing simulates; an object with no collider has no body; and a script
that runs before its own collider is declared asks too early. Asked in useUpdate, it is found
as soon as there is one.
Parameters
objectTGameObjectThe object whose body is wanted: self in a script, useSelf() while one is
built, or any object found or spawned.
Example
import { createMesh, createScene, useCubeGeometry, useSpawn, usePhysicsBody3d, usePhysicsWorld3d, useSelf } from 'nacatamalon';
import { getPhysicsBody3d } from 'nacatamalon/physics3d';
const Gate = () => {
createMesh({ geometry: useCubeGeometry(), tint: '#4a8cff', transform: { y: 1 } });
usePhysicsBody3d({ body: 'static', collider: { shape: 'box', size: [1, 1, 1] }, sensor: true });
// What went through it, by name.
getPhysicsBody3d(useSelf())?.onEnter((other) => {
console.log(`${other.name} went through`);
});
};
const Level = () => {
usePhysicsWorld3d();
useSpawn(Gate)();
return createScene();
};
View source · physics/box3d/provider.ts:118#getPhysicsWorld3dfunctionnacatamalon/physics3d
getPhysicsWorld3d() => TPhysicsWorldHandle3d | null
The 3D physics world the running scene built, or null if it has none.
The seam between authored data and authored behaviour, and the twin of the 2D adapter's
accessor of the same name. A collider is data: the scene declares it and this provider
simulates it, with no code on either side. Steering is not, and neither is a character, a
ray or a trigger's answer, so this is the way back out.
To move or listen to one object's body, getPhysicsBody3d(object) is the way: it needs no world.
null is an ordinary answer, not an error, and scripts must handle it: a tool that opens a
scene to edit it deserializes the same objects with no provider registered, so a script
runs there with no world and must simply do nothing. That is what keeps a workspace from
simulating while somebody is building in it.
registerScript('lookout', () => {
const world = getPhysicsWorld3d();
if (!world) return; // editing, not playing
useUpdate(() => {
// What is under the middle of the room: a question only the world can answer.
const hit = world.raycast({ x: 0, y: 10, z: 0 }, { x: 0, y: -1, z: 0 });
if (hit) console.log(`${hit.box.name} is ${hit.distance} below`);
});
});
Call it while the scene is being built, which is when a script runs, so this is the ordinary
case. Outside that there is no active game to compare against and the answer is always null.
View source · physics/box3d/provider.ts:67#installPhysics3dfunctionnacatamalon/physics3d
installPhysics3d() => void
Installs this as what simulates the solid half of a scene's physics. The one line a game
writes, and the only one: everything else about physics is the engine's vocabulary, so a scene
says what it is made of and this makes it move.
It is a call and not something that happens on import, for three separate reasons, any one of
which would be enough. The engine declares itself free of side effects, so a bundler is allowed
to drop an import nothing is used from, and a game that worked in development would sit still
once built. A tool must be able to open a scene and NOT simulate it, which is what lets you build
a level in a workspace that holds still. And a game may install the flat half as well, which it
does the same way, by saying so.
import { installPhysics3d } from 'nacatamalon/physics3d';
installPhysics3d();
Installing twice does nothing the second time.
View source · physics/box3d/provider.ts:271#loadPhysics3dfunctionnacatamalon/physics3d
loadPhysics3d() => Promise<void>
Loads what simulates the 3D physics, ahead of the first scene that needs it: once a page, however
often it is called. A world loads it on its own the first time, and its bodies wait for it, so this
is only for a game that would rather pay that wait on a loading screen than in its first level.
Example
import { installPhysics3d, loadPhysics3d } from 'nacatamalon/physics3d';
installPhysics3d();
await loadPhysics3d();
View source · physics/box3d/load_box3d.ts:76#physics3dProvidervariablenacatamalon/physics3d
physics3dProvider: TPhysicsProvider
Moves the physics a scene declares in three dimensions, using box3d.
This is the adapter's half of the split: the engine keeps colliders, writes them down and reads
them back while deliberately being unable to move them, and registering this is what makes a
scene actually fall. Nothing here is needed to author physics: a tool opens, edits and saves
a scene with none of it installed.
It is handed everything a scene declares, whether that came from a file or from a line somebody
typed, because the engine records it and then asks. There is nothing here that only one of those
two paths goes through.
import { registerPhysicsProvider } from 'nacatamalon/extend';
import { physics3dProvider } from 'nacatamalon/physics3d';
registerPhysicsProvider(physics3dProvider);
Properties
createWorld(world: TPhysicsWorld) => voidCalled once for the world a scene declares, and always before any body of that scene: the
world lives on the scene's root, and a root is built before what is under it.
createBody(box: TBox, body: TPhysicsBody) => voidCalled for each object carrying a collider. box is the object that owns it: where it starts
and where the simulation writes back to.
watchContactsoptional(box: TBox, told: (other: TBox, started: boolean) => void) => booleanTells told from now on whenever the body of box starts or stops touching another, with the
other's box: what collisions asked by component or by tag count. Answers whether it is the one
simulating that body, so the engine knows to ask no other. Optional: a provider without it
only leaves physics out of those collisions.
hasBodyoptional(box: TBox) => boolean | undefinedWhether box still has a body here: true or false when this provider simulates it, and
undefined when it is not this provider's. A body taken away while its object stays touches
nothing any more. Optional, like watchContacts.
createCharacter2doptional(box: TBox, shape: TCharacterShape2d) => TCharacterBody2d | undefinedA platformer's character for useTileBody2d on box, when this provider moves the scene the
object is in and has a character of its own, which then walks among its bodies as well as on
the maps. undefined leaves it to the character that walks on the maps alone. Optional.
drawDebugoptional(scene: TBox, draw: TDebugDraw) => voidDraws what this provider moves in scene for the debug mode (useGame().setDebugEnabled),
once a frame while it is on. The engine already draws the colliders of the full simulation
from what each object keeps, the hitboxes and the maps' tiles; this is for what only the
provider knows. Optional.
View source · physics/box3d/provider.ts:187#useCharacterBody3dfunctionhooknacatamalon/physics3d
useCharacterBody3d(options: TCharacterOptions3d) => TCharacterBody3d
Makes this object a walking character: a capsule moved by asking the world what is in the
way, and the thing that makes a room walkable.
It is the one part of physics that a scene cannot write down, and that is not an oversight. A
crate is a shape with a weight, and a file can say so. A character is a decision taken sixty
times a second about where a body is allowed to be: it climbs a step without jumping, walks up a
ramp and not up a wall, and stops dead against a crate instead of tipping over it. None of that
is a property of the object, so there is nothing for a scene to keep, and steering one with
forces gives you something that slides on slopes and falls over on its face.
Set velocity and it walks. Falling is applied for you, and isOnGround is the answer to
whether it may jump.
With no world to walk in, as in a tool opening the scene to edit it, it is a character that never
moves, so the game's code runs the same and nothing happens. When physics is installed and the
scene forgot its world, it says so once.
const Player = () => {
useTransform({ x: 0, y: 1, z: 0 });
createMesh({ geometry: useSphereGeometry({ radius: 0.35 }), tint: BLUE });
const player = useCharacterBody3d({ radius: 0.35, height: 1.8 });
const keys = useKeyboard();
useUpdate(() => {
player.velocity.x = keys.isDown('d') ? 4 : keys.isDown('a') ? -4 : 0;
if (keys.isDown('Space') && player.isOnGround) player.velocity.y = 5;
});
};
View source · physics/box3d/use_character_body_3d.ts:54#TCharacterBody3dtypenacatamalon/physics3d
A kinematic character: the thing that separates "boxes that fall" from "somebody walks here".
A character is deliberately not a dynamic body. A dynamic capsule steered by forces fights
its own momentum and friction: it slides on slopes, tips over, skates after you let go of the
stick, and catches on the seam between two floor tiles. Every engine solves this the same way
and so does this one: the character is a capsule moved by queries against the world
(b3World_CollideMover + b3SolvePlanes, Box2D v3's mover primitives), resolved to a position
that does not overlap anything, then written onto the box's transform.
Set TCharacterBody3d.velocity, and the world advances it on its own fixed step. Gravity is applied for you (set gravity: 0 for a
flyer), because a controller that falls is what "character" means to nearly everyone asking
for one.
Properties
velocity{ x, y, z }Metres per second, mutable in place: write into it from a useUpdate and the next
step uses it. This is the whole steering surface: horizontal components walk, a positive
y jumps, and gravity pulls y down between steps.
Re-assert it every frame, not once. The controller clips this vector against whatever
the character is touching, which is what makes a wall stop you and what keeps gravity from
accumulating while you stand still. The same clipping eats a walk that was set once: on a
slope, the part of the velocity pointing into the surface is removed every step, so a
"set and forget" walk decays within a second and the character slides back down.
isOnGroundbooleanWhether a surface flat enough to stand on is underfoot, decided from the contact planes of
the step just taken (normal.y >= cos(slopeLimit)), so a wall never counts and a ramp
steeper than the limit slides you off instead of letting you climb it.
setPosition(x: number, y: number, z: number) => voidPlaces the character without consulting the world: spawning, respawning, a cutscene. The
ordinary way to move is TCharacterBody3d.velocity; this is the escape hatch, and it
can put you inside a wall, which is why it is not the ordinary way.
destroy() => voidStops driving the object, which keeps whatever placement it last had.
View source · physics/box3d/character_body.ts:46#TCharacterOptions3dtypenacatamalon/physics3d
Everything a character needs beyond its world: the capsule it occupies, how it treats slopes,
and where that capsule sits inside its box.
height is the total height including the caps, the same convention Collider3D's capsule
uses, so a 1.8 m person is { radius: 0.3, height: 1.8 }.
Properties
radiusnumberheightnumberslopeLimitoptionalnumberThe steepest surface that still counts as ground, in radians. Default ~50°. Anything steeper is a wall as far as TCharacterBody3d.isOnGround is
concerned, so you slide down it rather than stand on it.
gravityoptionalnumberDownward acceleration in m/s², applied every step. Defaults to the world's own gravity
magnitude so a character falls at the same rate as everything around it. 0 for a flyer
or a top-down game.
offsetoptional[number, number, number]Where the capsule's centre sits relative to the box's origin, in local units before scale
which is the same field a collider carries, and needed for the same reason: a character model
from a glTF almost always has its origin at its feet, so a capsule centred on the
origin would bury the character's legs in the floor.
layeroptionalnumberThe collision layer the character's presence proxy is on, and which layers may see it
read exactly like a collider's (see the engine's TPhysicsSurface), because it is one.
This is what a trigger volume filters on. A door that should open for the player and not
for a wandering crate puts the player on its own layer and collides with that alone,
rather than checking a name at runtime.
The proxy is excluded from every mover query by its MASK (see MOVER_CATEGORY) rather than
by its category, so layer stays free to narrow who may notice it. Omitted means layer 0
against everything, the same default a collider has.
collidesWithoptionalnumber
View source · physics/box3d/character_body.ts:88#TColliderOptions3dtypenacatamalon/physics3d
TColliderOptions3d: TColliderSurface3d & { offset }
What every add* takes beyond its own dimensions: the surface, plus where the shape sits
inside the object.
offset is in the box's local units before its scale, matching
TPhysicsBody3d.offset, and it exists for glTF, which puts a model's origin at its
feet while a collider is centred on that origin. Omitted means centred.
Properties
offsetoptional[number, number, number]bounceoptionalnumberfrictionoptionalnumberdensityoptionalnumbersensoroptionalbooleanlayeroptionalnumberWhich collision layer this body is on (0..15) and which layers it collides with (a
bitmask): see the engine's TPhysicsSurface. Omitted means layer 0 against everything, which
is how every body behaved before layers existed.
collidesWithoptionalnumber
View source · physics/box3d/types.ts:271#TColliderSurface3dtypenacatamalon/physics3d
Optional surface tuning for a collider: how a contact resolves, and whether it resolves at
all. bounce is how much it bounces (0 = dead, 1 = elastic), friction resists sliding,
density (kg/m³) sets the body's mass from its volume, and sensor detects overlaps
without resolving them, which is a trigger volume. All optional; omitted fields keep Box3D's
defaults.
The grouping mirrors the engine's TPhysicsSurface, which puts the same four together for the same
reason: they are the non-geometric half of a collider.
Properties
bounceoptionalnumberfrictionoptionalnumberdensityoptionalnumbersensoroptionalbooleanlayeroptionalnumberWhich collision layer this body is on (0..15) and which layers it collides with (a
bitmask): see the engine's TPhysicsSurface. Omitted means layer 0 against everything, which
is how every body behaved before layers existed.
collidesWithoptionalnumber
View source · physics/box3d/types.ts:106#TPhysicsBodyHandle3dtypenacatamalon/physics3d
A runtime handle to one simulated body. Runtime only: the body lives in WASM
memory, so nothing here is serializable (the serializable form is the mesh's own
transform, which this body writes into).
Properties
onEnteronExitapplyImpulse(x: number, y: number, z: number) => voidApplies an instantaneous impulse (mass·velocity) at the body's center, waking
it. Queued if the WASM world is still loading, then flushed on materialization.
applyForce(x: number, y: number, z: number) => voidApplies a continuous force (mass·acceleration) at the body's center. Unlike an impulse
this is meant to be applied every frame: one call is one frame's worth of push.
applyTorque(x: number, y: number, z: number) => voidApplies a continuous torque about the body's center, the rotational sibling of
TPhysicsBodyHandle3d.applyForce.
setLinearVelocity(x: number, y: number, z: number) => voidSets the body's velocity outright, overriding whatever the solver had. This is how a
character walks: forces fight momentum and friction, a velocity set does not.
setAngularVelocity(x: number, y: number, z: number) => voidSets the body's spin outright, the rotational sibling of setLinearVelocity.
setLayers(layer: TPhysicsLayer, collidesWith?: number | typeOperator) => voidMoves the body to another collision layer, and changes what it collides with, while the game
runs: a player who passes through enemies for a moment after being hit. The same two values
the body was created with (see the engine's TPhysicsSurface), and the same mutual rule: two
bodies meet only if each one's mask includes the other's layer.
collidesWith left out keeps the mask the body already had. The object's physics record is
updated too, so a scene saved afterwards keeps the layers it is simulating with.
destroy() => voidRemoves this body from the simulation, freeing its WASM memory. The object stops being
driven and keeps whatever placement it last had. Safe to call twice; the world's own
teardown skips bodies already destroyed this way.
View source · physics/box3d/types.ts:31#TPhysicsWorldHandle3dtypenacatamalon/physics3d
The world a scene declared, and the factory for bodies in it. Deliberately narrow (box + sphere for now); more shapes and queries land
when a concrete case needs them, not before.
Properties
addBox(box: TGameObject, opts: { type, size } & TColliderOptions3d) => TPhysicsBodyHandle3dAdds a box collider whose full extents are size (metres, halved internally to
Box3D's half-extents), positioned and turned from where the object is.
addSphere(box: TGameObject, opts: { type, radius } & TColliderOptions3d) => TPhysicsBodyHandle3dAdds a sphere collider of radius (metres), positioned from where the object is.
addCapsule(box: TGameObject, opts: { type, radius, height } & TColliderOptions3d) => TPhysicsBodyHandle3dAdds a capsule collider standing on Y: a cylinder with hemispherical caps, and what a
character should use: a box catches on floor seams and step lips, a capsule rides over
them.
height is the total height including the caps (see TCollider3d), which is not how
Box3D states it, because it wants two cap centres. The conversion happens here, and a height
below radius * 2 clamps to a sphere rather than inverting the shape.
addHull(box: TGameObject, opts: { type, geometry } & TColliderOptions3d) => TPhysicsBodyHandle3dAdds the convex hull of a geometry's vertices: the collider for a prop whose silhouette
matters but whose hollows do not. Cheap to collide against and valid for a dynamic body,
which is what separates it from addMesh.
Reads the shape's corners, so it works on an imported glTF as well as on a
primitive. A model still loading has no positions yet and produces an empty body rather
than throwing, which is the same deferral every other shape already survives.
addMesh(box: TGameObject, opts: { type, geometry } & TColliderOptions3d) => TPhysicsBodyHandle3dAdds the geometry's actual triangles, concave and all. This is level geometry:
terrain, a room, a track.
Static or kinematic only. A triangle mesh is a surface with no interior, so a dynamic body
made of one has nothing to be pushed out of; 'dynamic' is clamped to 'static' with a
warning rather than silently falling through the world.
addCharacter(box: TGameObject, opts: TCharacterOptions3d) => TCharacterBody3dAdds a kinematic character: a capsule moved by queries rather than by forces, and the
thing that makes a world walkable. See TCharacterBody3d for why it is not a body.
It is advanced by this world's own fixed step, like everything else here, so nothing has to
be called per frame: write into velocity whenever, and the character walks.
raycast(origin: { x, y, z }, direction: { x, y, z }, opts?: TRaycastOptions) => TRaycastHit | nullFires a ray and returns the closest thing it hits, or null for a clean miss, and the
first query on this surface that is not about creating something.
A ray is how a game asks a question it cannot answer from its own state: what is under the
cursor, is there ground beneath these feet, can the guard see the player, what did this gun
shoot. All four are the same call.
direction need not be normalized: its length is ignored and maxDistance is what
decides how far the ray reaches. That is not Box3D's shape (which takes a single translation
vector meaning both at once), because "which way" and "how far" are
separate thoughts and combining them is how a ray silently ends up 0.3 m long.
Returns null while the WASM runtime is still loading, exactly as every other call here
defers: a ray cast on the first frame of a scene is not an error, it is early.
View source · physics/box3d/types.ts:128#TPhysicsWorldOptions3dtypenacatamalon/physics3d
Options for the world. gravity is metres/second² (the engine's 3D unit is one
metre); it defaults to Earth on -Y.
Properties
gravityoptional{ x, y, z }
View source · physics/box3d/types.ts:281#TRaycastHittypenacatamalon/physics3d
What a ray found: which object, where, and how far along.
box is the very object handed to addBox/addSphere and the rest, so a hit is immediately
usable ("move this", "damage that") without a lookup table of your own.
Properties
point{ x, y, z }Where the ray met the surface, in world metres.
normal{ x, y, z }The surface normal there, unit length and pointing out of the shape.
distancenumberMetres from origin to point.
View source · physics/box3d/types.ts:230#TRaycastOptionstypenacatamalon/physics3d
How far a ray reaches and what it is allowed to hit.
collidesWith is a layer bitmask read exactly like a body's own (see the engine's TPhysicsSurface)
so a ground check that should ignore enemies, or a cursor pick that should ignore scenery,
is the same vocabulary the colliders are already authored in rather than a second one.
Properties
maxDistanceoptionalnumberMetres. Defaults to DEFAULT_RAY_DISTANCE.
collidesWithoptionalnumberWhich layers the ray can hit. Defaults to all of them.
View source · physics/box3d/types.ts:209nacatamalon/retro-physics2d
#castRetroRay2dfunctionnacatamalon/retro-physics2d
castRetroRay2d(from: TGameObject, origin: { x, y }, direction: { x, y }, options: TRetroRayOptions2d) => TRetroRayHit2d | null
Casts a ray through the retro world of from's scene and gives the nearest body or tile it meets:
what is under the feet, whether the guard sees the player, where the shot lands. from is the
object asking, and the ray never meets its own body.
Bodies are measured where their objects are now, sensors left out, and the maps as they are: a
solid tile by the side the ray enters, a slope by its surface, a ledge only from above.
Parameters
fromTGameObjectThe object asking: its scene's world is searched, and its own body left out.
origin{ x, y }Where the ray starts, in the world.
direction{ x, y }Which way it goes; its length does not matter.
optionsTRetroRayOptions2dHow far it reaches, which layers of bodies it meets, and whether it meets tiles.
Example
import { createSprite, useRetroBody2d, useSelf, useUpdate } from 'nacatamalon';
import { castRetroRay2d } from 'nacatamalon/retro-physics2d';
const Guard = () => {
const sprite = createSprite({ key: 'guard', transform: { x: 200, y: 100 } });
useRetroBody2d({ body: 'dynamic', collider: { shape: 'rect', width: 12, height: 24 } });
const self = useSelf();
useUpdate(() => {
// Is there floor a step ahead? Turn round at the edge.
const ahead = sprite.flipX ? -10 : 10;
const floor = castRetroRay2d(self, { x: sprite.transform.x + ahead, y: sprite.transform.y }, { x: 0, y: 1 }, { maxDistance: 20 });
if (floor === null) sprite.flipX = !sprite.flipX;
});
};
View source · physics/retro2d/provider.ts:212#findRetroBodies2dfunctionnacatamalon/retro-physics2d
findRetroBodies2d(from: TGameObject, area: TRetroArea2d, options: TRetroAreaOptions2d) => TGameObject[]
The objects whose retro bodies are in a part of from's world now, the nearest to its middle
first: what an explosion reaches, the enemies a guard can hear, the coins a magnet pulls. from
is the object asking, and is left out.
The area is a rectangle from its top left corner, { x, y, width, height }, or a circle from its
middle, { x, y, radius }, in the world's pixels. Sensors count unless sensors: false.
Parameters
fromTGameObjectThe object asking: its scene's world is searched, and it is left out.
areaTRetroArea2dThe part of the world, a rectangle or a circle.
optionsTRetroAreaOptions2dWhich layers count, and whether sensors do.
Example
import { destroy, useSelf } from 'nacatamalon';
import { findRetroBodies2d } from 'nacatamalon/retro-physics2d';
const Bomb = (x: number, y: number) => {
const self = useSelf();
// Everything within 40 pixels goes with it.
const explode = () => {
for (const hit of findRetroBodies2d(self, { x, y, radius: 40 }, { collidesWith: ['enemy'] })) destroy(hit);
destroy(self);
};
void explode;
};
View source · physics/retro2d/provider.ts:293#getRetroBody2dfunctionnacatamalon/retro-physics2d
getRetroBody2d(object: TGameObject) => TRetroBodyHandle2d | null
Gives the retro body that moves an object, to push, listen and read what stopped it. null for an
object with no retro body, or before the retro physics is installed.
It is the same body getPhysicsBody2d would give for a body of the full simulation, with what the
retro half adds: velocity, acceleration and blocked.
Parameters
objectTGameObjectThe object whose body it is.
Example
import { createSprite, useKeyboard, useRetroBody2d, useSelf, useUpdate } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';
const Hero = () => {
createSprite({ key: 'hero', transform: { x: 40, y: 100 } });
useRetroBody2d({ body: 'dynamic', collider: { shape: 'rect', width: 12, height: 24 } });
const body = getRetroBody2d(useSelf());
const keys = useKeyboard();
useUpdate(() => {
if (body === null) return;
body.velocity.x = ((keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0)) * 90;
if (keys.justPressed('x') && body.blocked.down) body.velocity.y = -300;
});
};
View source · physics/retro2d/provider.ts:81#installRetroPhysics2dfunctionnacatamalon/retro-physics2d
installRetroPhysics2d() => void
Installs the retro half of physics: bodies that never turn, moved in pixels a fixed step at a time
and stopped against each other axis by axis. The one line a game writes to make its retro
bodies move, beside or instead of installPhysics2d().
import { installRetroPhysics2d } from 'nacatamalon/retro-physics2d';
installRetroPhysics2d();
Installing twice does nothing the second time.
View source · physics/retro2d/provider.ts:249#isRetroAreaFree2dfunctionnacatamalon/retro-physics2d
isRetroAreaFree2d(from: TGameObject, area: TRetroArea2d, options: TRetroAreaOptions2d) => boolean
Whether a part of from's world is empty of anything solid now: no retro body that stops things
(sensors never count), and no solid tile of the maps unless tiles: false. Whether a crate fits
where it is about to be dropped, whether a character can stand up from a crouch.
Parameters
fromTGameObjectThe object asking: its scene's world is searched, and it is left out.
areaTRetroArea2dThe part of the world, a rectangle from its top left or a circle from its middle.
optionsTRetroAreaOptions2dWhich layers of bodies count, and whether the maps do.
Example
import { useSelf } from 'nacatamalon';
import { isRetroAreaFree2d } from 'nacatamalon/retro-physics2d';
const Hero = () => {
const self = useSelf();
// Room above the head to stand up again?
const canStand = (x: number, top: number) => isRetroAreaFree2d(self, { x: x - 6, y: top - 12, width: 12, height: 12 });
void canStand;
};
View source · physics/retro2d/provider.ts:323#retroPhysics2dProvidervariablenacatamalon/retro-physics2d
retroPhysics2dProvider: TPhysicsProvider
Moves the retro bodies a scene declares: the provider installRetroPhysics2d() installs.
It takes only what is its own, retro-world-2d and retro-body-2d, and leaves the rest to the
other providers, so it can be installed beside the full simulation: each scene is moved by the
kind of world it declares.
import { registerPhysicsProvider } from 'nacatamalon/extend';
import { retroPhysics2dProvider } from 'nacatamalon/retro-physics2d';
registerPhysicsProvider(retroPhysics2dProvider);
Properties
createWorld(world: TPhysicsWorld) => voidCalled once for the world a scene declares, and always before any body of that scene: the
world lives on the scene's root, and a root is built before what is under it.
createBody(box: TBox, body: TPhysicsBody) => voidCalled for each object carrying a collider. box is the object that owns it: where it starts
and where the simulation writes back to.
watchContactsoptional(box: TBox, told: (other: TBox, started: boolean) => void) => booleanTells told from now on whenever the body of box starts or stops touching another, with the
other's box: what collisions asked by component or by tag count. Answers whether it is the one
simulating that body, so the engine knows to ask no other. Optional: a provider without it
only leaves physics out of those collisions.
hasBodyoptional(box: TBox) => boolean | undefinedWhether box still has a body here: true or false when this provider simulates it, and
undefined when it is not this provider's. A body taken away while its object stays touches
nothing any more. Optional, like watchContacts.
createCharacter2doptional(box: TBox, shape: TCharacterShape2d) => TCharacterBody2d | undefinedA platformer's character for useTileBody2d on box, when this provider moves the scene the
object is in and has a character of its own, which then walks among its bodies as well as on
the maps. undefined leaves it to the character that walks on the maps alone. Optional.
drawDebugoptional(scene: TBox, draw: TDebugDraw) => voidDraws what this provider moves in scene for the debug mode (useGame().setDebugEnabled),
once a frame while it is on. The engine already draws the colliders of the full simulation
from what each object keeps, the hitboxes and the maps' tiles; this is for what only the
provider knows. Optional.
View source · physics/retro2d/provider.ts:101#TRetroArea2dtypenacatamalon/retro-physics2d
TRetroArea2d: { x, y, width, height } | { x, y, radius }
A part of the world, in its pixels: a rectangle from its top left corner, or a circle from its
middle.
View source · physics/retro2d/types.ts:76#TRetroAreaOptions2dtypenacatamalon/retro-physics2d
Which bodies a question about a part of the world counts.
Properties
collidesWithoptionalnumber | typeOperatorThe layers of the bodies it counts, by number, mask or name. Every layer when left out.
sensorsoptionalbooleanWhether sensors count. findRetroBodies2d counts them unless told not to (the coins near the
player); isRetroAreaFree2d never does, since nothing is stopped by one.
tilesoptionalbooleanWhether the maps' solid tiles fill the area, for isRetroAreaFree2d. true when left out.
View source · physics/retro2d/types.ts:264#TRetroBlockedtypenacatamalon/retro-physics2d
Which sides of a retro body something stopped in its last step: a wall on the left, the ground
under it. Pushing a crate that gives way is not being stopped; pushing one against a wall is.
Properties
leftbooleanrightbooleanupbooleandownboolean
View source · physics/retro2d/types.ts:15#TRetroBodyHandle2dtypenacatamalon/retro-physics2d
TRetroBodyHandle2d: Omit<TPhysicsBodyHandle2d, 'onEnter' | 'onExit'> & { velocity, acceleration, speed, blocked, touching, wasTouching, angularVelocity, angularAcceleration, angularDrag, onEnter, onExit, onTileEnter, onTileExit, onBounds, collidesIf, moveTowards, accelerateTowards, setVelocityFromAngle }
A retro body as the game drives it: everything a body of the full simulation offers, so code
written against getPhysicsBody2d works on it, and what the retro half adds.
Its position is the object's: move the object and the body is there on the next step, with
nothing to tell. How it moves and what it is made of are its record's (bounce, drag,
maxSpeed, gravityScale, mass, enabled, pushable, solidSides, bounds, carries, and its
collider's size), read every step, so changing the record that useRetroBody2d returned changes
the body: a smaller collider while crouching, off while blinking.
Its collider never turns. setAngularVelocity and the angular fields turn its picture, the
object, which a ball rolling or a coin spinning wants.
Properties
velocity{ x, y }Pixels per second, read and written by the game: x walks, a negative y jumps. Gravity,
pushes and what it hits change it between steps.
acceleration{ x, y }Pixels per second squared added to its speed every step until the game changes it: an engine
that keeps pushing. While an axis has none, drag slows that axis.
speednumberIts whole speed, in pixels per second, whichever way it goes.
blockedTRetroBlockedWhich sides something stopped in its last step: what it pushed against and could not move.
touchingTRetroTouchingWhich sides touch something now, pressed or not, and which did a step before: touching.down
and not wasTouching.down is the step it landed.
angularVelocitynumberHow fast its picture turns, in radians per second, and what speeds it up and slows it down.
Its collider stays square to the screen.
angularAccelerationnumberangularDragnumberonEnteronExitonTileEnteronTileExitonBoundscollidesIfmoveTowardsaccelerateTowardssetVelocityFromAngle
View source · physics/retro2d/types.ts:104#TRetroContact2dtypenacatamalon/retro-physics2d
How two retro bodies met, as one of them is told it: which of its sides the other is on, and how
fast they were closing when they met, in pixels per second. What a landing sound, or damage from a
fall, is worked out from.
View source · physics/retro2d/types.ts:50#TRetroRayHit2dtypenacatamalon/retro-physics2d
What a retro ray met: a body or a tile of a map, where, the way its surface faces there, and how
far along the ray.
Properties
objectTGameObject | nullThe object whose body it met, or null for a tile.
cell{ map, column, row } | nullThe cell of the map it met, or null for a body: what setTile takes to break a brick.
tileTTileDoc | undefinedWhat the file says about that tile (props, damage…), or undefined for a body.
point{ x, y }Where the ray met it, in the world.
normal{ x, y }The way its surface faces there, one pixel long: up on a floor, square to the line of a slope.
distancenumberPixels from where the ray started.
View source · physics/retro2d/types.ts:207#TRetroRayOptions2dtypenacatamalon/retro-physics2d
How far a retro ray reaches and what it may meet.
Properties
maxDistanceoptionalnumberPixels. As far as anything is, when left out.
collidesWithoptionalnumber | typeOperatorThe layers of the bodies it meets, by number, mask or the names the game gave them. Every
layer when left out. Tiles have no layer.
tilesoptionalbooleanWhether it meets the maps' solid tiles, slopes and ledges (from above). true when left out.
View source · physics/retro2d/types.ts:241#TRetroSidetypenacatamalon/retro-physics2d
TRetroSide: 'up' | 'down' | 'left' | 'right'
View source · physics/retro2d/types.ts:29#TRetroTargettypenacatamalon/retro-physics2d
TRetroTarget: { x, y } | TGameObject
Where something is to head for: a point of the world, or an object, followed wherever it goes.
View source · physics/retro2d/types.ts:85#TRetroTileTouch2dtypenacatamalon/retro-physics2d
A tile a retro body touches: what the file says about it, and where it is, with its layer, as
setTile takes it to take a coin out of the map.
Properties
cell{ map, layer, column, row }
View source · physics/retro2d/types.ts:63#TRetroTouchingtypenacatamalon/retro-physics2d
TRetroTouching: TRetroBlocked
Which sides of a retro body touch something, pressed against it or only resting beside it: a
body, a solid tile, the ground, an edge of the world.
Properties
leftbooleanrightbooleanupbooleandownboolean
View source · physics/retro2d/types.ts:39