# Entities Entities are the things in the world that aren't blocks and move on their own: animals, dropped items, the fishing hook, and players. Mods define new kinds in their `entities/` folder, and draw them with a model from `models/`. ## Defining an Entity `entities/chicken.json`: ```json { "format_version": 1, "entity": { "id": "bworld:chicken", "model": "bworld:chicken", "texture": "bworld:chicken", "width": 0.3, "height": 0.4, "max_health": 4, "movement_speed": 0.25 } } ``` | Field | Default | Meaning | | -------------------- | ---------- | ------------------------------------------------------------------------------------------------------ | | `id` | required | The entity's id. | | `texture` | required | Any texture, stretched over the model's `texture_width` and `texture_height`. An object needs none. | | `model` | none | An [entity model](#entity-models). Without one it's drawn as its texture, facing the camera. | | `behavior` | `"animal"` | `"animal"`, `"monster"`, `"scripted"`, `"object"`, or a [custom behavior](#custom-behaviors)'s id. | | `scale` | `1` | How much bigger it's drawn than its model, texture or item. Its box stays `width` and `height`. | | `category` | see below | `"monster"` or `"creature"`, see [Natural Spawning](#natural-spawning). | | `width`, `height` | required | Its collision box in blocks, up to 16. `width` is for both x and z. Its eyes are at 85% of the height. | | `max_health` | `10` | In half hearts. | | `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. | | `jumps` | `true` | Whether it jumps onto blocks in its way. Without, it still steps up 0.6 blocks and swims up in water. | | `max_fall` | `3` | How many blocks it drops on its way. `0` never walks off an edge, to keep monsters out of pits. | | `attack_damage` | `2` | What a monster's hits do, in half hearts. | | `physical_shielding` | `0` | Protection from physical damage. Not used yet. | | `arcane_shielding` | `0` | Protection from arcane damage. Not used yet. | | `loot_table` | none | A [loot table](../resources/loot_tables.md) it drops from when it dies. | | `sounds` | silent | What its sounds' ids start with, see [Sounds](../resources/sounds.md#blocks-and-entities). | `/summon ` spawns one where you stand. ## Behaviors **Animals** (the default) are mobs: they wander around, panic when hurt, look at players now and then, swim up in water, and never despawn. They're saved with the world, and players can't place solid blocks where one is standing. Players hit animals, and each other, by left clicking them from up to 3 blocks away, for 1 physical damage (half a heart) whatever they hold. The hit pushes them away, and like any damage it can't hurt them again for half a second unless it's harder. See [Players](players.md#health-and-hunger). **Monsters** go after the nearest player they can see within 16 blocks, and whoever last hurt them, before anyone else. They find their way to it (see [Getting Around](#getting-around)) and hit it for `attack_damage` once a second, swinging their right arm. Otherwise they wander around and look about. Unlike animals, they go away when no player is near. The Rotwalker in `mods/undergarden` is one: ```json { "format_version": 1, "entity": { "id": "undergarden:rotwalker", "model": "undergarden:rotwalker", "texture": "undergarden:rotwalker", "behavior": "monster", "width": 0.8, "height": 2.5, "max_health": 40, "movement_speed": 0.23, "attack_damage": 5, "physical_shielding": 3 } } ``` Monsters can also [spawn on their own](#natural-spawning) in the dark. **Scripted** entities stay exactly where a script puts them. They don't fall, think or get hurt, and aren't saved with the world, so a script never finds one it doesn't know about after a restart. The fishing hook is one: ```json { "format_version": 1, "entity": { "id": "bworld:fishing_hook", "texture": "bworld:fishing_hook", "behavior": "scripted", "width": 0.25, "height": 0.25 } } ``` **Objects** lie around like a dropped item, holding one: they fall, slide and float in water the same way, but nobody picks them up by walking into them, and they never despawn or merge. They can't be hurt, don't think, don't stop blocks being placed where they are, and are saved with the world with what they hold. Without a `model`, an object is drawn as its item: the item's [model](../resources/models.md#entity-models-as-items) at the size it's made, times `scale`, turned the way the object faces. An item lies around as an object instead of a dropped item when it names one as its [`entity`](../items/index.md#properties), like NeoForge's `hasCustomEntity`. Every way an item ends up in the world spawns the object holding it: thrown, dropped when its holder dies or when it doesn't fit, popped out of a broken block, or a script's `spawn_item` or `drop_item`. Dangerous Business's scrap is one, picked up by right clicking it (see [Interacting](#interacting)): ```json { "format_version": 1, "entity": { "id": "dangerous_business:scrap", "behavior": "object", "width": 0.7, "height": 0.7, "scale": 0.7 } } ``` ## Interacting Right clicking an entity from up to 3 blocks away fires [`before.entity_interact`](../concepts/events.md#the-events), like NeoForge's `PlayerInteractEvent.EntityInteract`. Its handlers do whatever the click does and cancel it, otherwise the held item is used as if clicking nothing. A handler can also leave the entity be, like scrap with nowhere to go: ```ts ctx.events.before.entity_interact.subscribe((event) => { if (event.entity.type !== "dangerous_business:scrap") return; event.cancel = true; const item = event.entity.get_item(); const slot = [0, 1, 2, 3].find((slot) => event.player.inventory.get(slot) === undefined); if (!item || slot === undefined) return; event.player.inventory.set(slot, item); event.entity.remove(); }); ``` ## Custom Behaviors A mob can get its goals from a script instead, like NeoForge's `registerGoals`. Its json names a behavior id, and the server phase registers a function under that id, which runs once for each mob of that kind before it first thinks: ```json "behavior": "my_mod:sentry" ``` ```ts export function server(ctx: ServerContext) { const chase = ctx.entities.goals.melee_attack({ speed: 1.25 }); ctx.entities.register_behavior("my_mod:sentry", (mob, goals) => { // stands still at night, taking every control from the goals after it goals.add(0, { flags: ["move", "look", "jump"], can_use: () => ctx.world.hour < 6 || ctx.world.hour >= 18, start: () => mob.stop(), }); goals.add(1, chase); goals.add_target(0, ctx.entities.goals.nearest_attackable_player()); }); } ``` A server won't start with an entity whose behavior nothing registered. Every tick, running goals that can't continue stop, then the ones that can start do, most important (lowest priority number) first, then every running goal ticks. A goal only starts once each of its `flags` is free or held by a less important goal, which then stops: `"move"`, `"look"`, `"jump"`, and `"target"` for the goals in `add_target` that pick who the mob goes after. | Goal field | Meaning | | ----------------------- | ---------------------------------------------------------------------- | | `flags` | The controls it needs while it runs. None when not given. | | `can_use()` | Whether it wants to start. The only one it needs. | | `can_continue_to_use()` | Whether it wants to keep going. `can_use` when not given. | | `is_interruptable()` | Whether a more important goal can take its flags. True when not given. | | `start()`, `stop()` | When it starts and stops running. | | `tick()` | Every tick while it runs. | A goal that throws is logged once and never runs again, and the mob's other goals go on. What a mob's goals have to remember goes in the behavior function's closures, which each mob gets its own of. `ctx.entities.goals` has the goals animals and monsters are made of, to add next to your own. One can be added to many mobs: | Goal | What it does | | ------------------------------------------------- | ------------------------------------------------------------------- | | `float()` | Swims up in water. | | `random_stroll({ speed?, interval?, range? })` | Walks to a random spot within `range` every `interval` ticks or so. | | `panic({ speed? })` | Runs around after being hurt or while burning. | | `look_at_player({ range?, probability? })` | Looks at a nearby player for a couple of seconds now and then. | | `random_look_around()` | Looks around at nothing in particular. | | `melee_attack({ speed?, interval? })` | Goes after its target and hits it, at most every `interval` ticks. | | `hurt_by_target()`, `nearest_attackable_player()` | Target goals: whoever hurt it last, the nearest player. | Speeds multiply its `movement_speed`. The mob a behavior gets is a `MobRef`, a [living entity](effects.md) with: ```ts interface MobRef extends LivingRef { readonly type: Id; readonly position: Readonly; readonly eye_position: Readonly; // where it sees from readonly look_direction: Readonly; // a vector 1 long readonly velocity: Readonly; // in blocks a second readonly on_ground: boolean; readonly in_water: boolean; target: Player | MobRef | undefined; // who it's after, undefined once they're dead or gone readonly last_attacker: Player | MobRef | undefined; random(): number; // 0 to 1, from the mob's own random move_to(x: number, y: number, z: number, speed?: number): boolean; // see Getting Around stop(): void; readonly moving: boolean; readonly blocked_by: { x: number; y: number; z: number; id: Id } | undefined; look_at(x: number, y: number, z: number): void; // for a couple of ticks, so call it every tick jump(): void; // this tick, or swims up in water attack(target: Player | MobRef): void; // swings and hits with its attack_damage // what clients see of its state, for its animator, see Animators get_client_data(field: string): T | undefined; set_client_data(field: string, value: unknown): void; } ``` Each mob has one `MobRef`, so `mob.target === player` works. Like any living entity, it has attributes that modifiers change, so a mob that speeds up the longer it chases can do it with a modifier on its speed: ```ts mob.add_modifier("cubi:movement_speed", { id: "my_mod:rush", amount: 0.4, operation: "add_multiplied_total" }); mob.remove_modifier("cubi:movement_speed", "my_mod:rush"); ``` ## Getting Around Mobs find their way around walls and through gaps, like Minecraft's pathfinding. `move_to` searches for a way and the mob walks it, and it's how strolling, panicking and going after a target get anywhere: - A way only goes where the mob's box fits, so a 2 tall mob doesn't fit under a 2 high gap. It steps onto anything up to 0.6 high, like a slab, jumps up 1 block when its `jumps` is on, and drops up to `max_fall` blocks. With `max_fall` 0 it never walks off an edge either, like a sneaking player, though something that knocks it into the air can still knock it off. - It looks up to its `follow_range` (16 blocks unless an attribute changes it) from where it is. When it can't get to the spot, it goes as close as it can and `move_to` still returns true. It returns false when it can't get any closer. - A search that didn't get the whole way is the slow kind, so for a second after one, `move_to` doesn't search again. - Stuck with no closer to its way for two seconds, it searches once more, then stops. Blocks in the [`#cubi:mobs_path_through`](../resources/tags.md#the-engines-tags) tag count as empty, solid or not, so a way can go through them. A mob pressed against a solid one on its way stops there with `blocked_by` set to it, and waits for as long as it stays solid and in the way. It's up to the behavior what happens then, like a goal without flags, so the mob keeps its way, that breaks the block after two seconds: ```ts let waited = 0; goals.add(0, { can_use: () => mob.blocked_by !== undefined, start: () => waited = 0, tick: () => { const { x, y, z } = mob.blocked_by!; if (++waited === 40) ctx.world.break_block(x, y, z); }, }); ``` ## Natural Spawning An entity's `category` is what natural spawning counts it as, like Minecraft's mob categories. Monsters can spawn on their own and go away when no player is near, creatures stay. Without one, a `"monster"` is a monster and anything else is a creature. Monsters spawn on their own in the dark around players, the way Minecraft's do. A mod lists which ones, how often and in which biomes in `worldgen/spawns.json`, like NeoForge's `add_spawns` biome modifier. The Undergarden's rotwalkers: ```json { "format_version": 1, "spawns": [ { "entity": "undergarden:rotwalker", "weight": 100, "min_count": 4, "max_count": 4, "chance": 0.1 } ] } ``` | Field | Default | Meaning | | ----------- | ----------- | --------------------------------------------------------------------------------------------------------------- | | `entity` | required | An entity in the `"monster"` category. Only monsters spawn on their own for now. | | `weight` | required | How often this one is picked over the others that can spawn in the same biome. | | `min_count` | required | How many spawn together, at least. | | `max_count` | required | And at most. | | `biomes` | every biome | Biome ids, like `["bworld:dark_forest", "bworld:swamp"]`. See [World Generation](../worldgen/index.md#terrain). | | `chance` | `1` | The chance a spawn that passed every other check goes ahead. The Undergarden gives its rotspawn 1 in 10. | Every tick, the server makes one try in each chunk within 6 chunks of a player that their client has loaded: 1. It picks a random spot in the chunk, anywhere from the bottom of the world to just above the surface, so most spawns are in caves. 2. From there, up to 3 groups wander up to 5 blocks a step at that height. The first spot of a group picks a spawn by `weight` from the ones for its biome, and the group tries to spawn between `min_count` and `max_count` of it, at most 4 from one try. 3. Each spot has to be at least 24 blocks from every player and from the world spawn, on top of a whole solid block (not leaves, glass or a block that gives off light 14 or more), with room for the entity's box and no water in it. 4. It has to be dark: no block light at all, and less likely the more sky light there is. Under the open sky monsters only spawn at night. There are at most 70 monsters for the 17x17 chunks around a player, fewer when fewer chunks are loaded. Monsters that never despawn (named, riding or ridden, or that picked up an item) don't count. Like any monster, they despawn when no player is near. ## Spawning From Scripts ```ts const hook = ctx.world.spawn_entity("bworld:fishing_hook", x, y, z); // feet at x, y, z hook.teleport(x, y + 0.1, z); if (!hook.removed) hook.remove(); ``` `spawn_entity` throws for a kind that doesn't exist, and returns an `EntityRef`: ```ts interface EntityRef { readonly id: string; // this entity's own id readonly type: string; // its kind, like "bworld:fishing_hook" readonly position: { x: number; y: number; z: number }; readonly biome: string; // where its feet are, see ../worldgen/biomes.md#seasons readonly season: Season; // that biome's readonly removed: boolean; readonly velocity: { x: number; y: number; z: number }; // in blocks a second readonly on_ground: boolean; // standing or lying on something teleport(x: number, y: number, z: number): void; push(x: number, y: number, z: number): void; // adds to its velocity remove(): void; kill(cause?: string): void; // players and mobs die, anything else is removed get_item(): ItemStack | undefined; // for an item lying around or what an object holds, a copy set_item(item: ItemStack | undefined): void; // undefined takes an item lying around away, an object holds nothing } ``` Once an entity is removed, by a script or anything else, it stays removed, and teleporting it does nothing. Check `removed` before relying on one you kept from earlier. `kill` is like NeoForge's `Entity.kill`: a player or a mob dies even when it's invulnerable, the way falling out of the world hurts it, and `cause` goes to `entity_damage` and the death message like [`damage`](players.md)'s does. Mods' `before.entity_damage` can still cancel it. Anything that can't die, like an item lying around, is removed instead. `push` adds to how fast it's moving, like Minecraft's `Entity.push`: a fan blowing it along does it every tick. Players have a `push` too, see [Players](players.md#pushing). ## Finding Entities `ctx.world.entities_in(from, to, type?)` finds the entities whose boxes overlap the box between two corners, like Minecraft's `getEntitiesOfClass`, only the ones of `type` when it's given. Players aren't among them, they're in `ctx.players`. Items lying around are entities of type `cubi:item`. A machine that works on them, like a press, finds them, changes them with `set_item`, and adds what it made with `ctx.world.spawn_item`, which lays an item down still where it's put, unlike `drop_item`, which pops it out of a block: ```ts const [item] = ctx.world.entities_in({ x, y: y - 1, z }, { x: x + 1, y, z: z + 1 }, "cubi:item"); const stack = item?.get_item(); if (stack?.id === "bworld:iron_ingot") { item.set_item(stack.count > 1 ? { ...stack, count: stack.count - 1 } : undefined); const { x: ix, y: iy, z: iz } = item.position; ctx.world.spawn_item(ix, iy, iz, { id: "create:iron_sheet", count: 1 }); } ``` ## Entity Models Entity models are `models/.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), and get the id `:`. From the file's first geometry, bworld uses: - the description's `texture_width` and `texture_height`, - each bone's `name`, `parent`, `pivot` and `rotation`, - each cube's `origin`, `size`, `uv`, `inflate`, `pivot` and `rotation`, - `item_display_transforms`, for an [item drawn with it](../resources/models.md#entity-models-as-items). Cubes can use box UV (`"uv": [u, v]`) or per face UV (`"uv": { "north": { "uv": [u, v], "uv_size": [w, h] }, ... }`), where a face that's left out isn't drawn and a negative size flips it. Faces are drawn from both sides, like Bedrock's `entity_alphatest` material, so a flat cube needs only one textured face. A bone's parent has to come before it. The model faces -z, 16 pixels to a block with its feet at 0, and shows the way Blockbench shows it. The whole model turns with the entity. An entity type with an [animator](#animations) has its bones posed by that. Without one, bones with Minecraft's humanoid names move on their own: - `head` turns to where the entity looks. - `right_arm`, `left_arm`, `right_leg` and `left_leg` swing as it walks, each arm with the opposite leg. - `right_arm` also comes down when a monster attacks. Without a model, the whole texture is drawn facing the camera, 16 pixels to a block, centered on the middle of the entity's box. ## Animations Animations are keyframes made in Blockbench, played by code in the mod's client script. This is how NeoForge does it too: JSON keyframes, applied by the model's own `setupAnim`. Bedrock's Molang expressions and animation controllers aren't used, since the animator does both in TypeScript. ### Clips `animations/.animation.json` are animation files as Blockbench exports them for Bedrock. Each animation in one is a clip, named after the file and the last part of the animation's name: `animation.coilhead.walk` in `animations/coilhead.animation.json` is `:coilhead/walk`. From each animation, bworld uses: - `animation_length`, in seconds, or the last keyframe's time without it, - `loop`: `true` loops. `false`, no `loop` and `"hold_on_last_frame"` all stay on the last frame after the clip's end, - each bone's `rotation` (degrees, added to the bone's own), `position` (pixels) and `scale`, as one value for the whole clip or keyframes by time. A keyframe is a number for all three axes, `[x, y, z]`, `{ "pre": ..., "post": ... }`, and can be `"lerp_mode": "catmullrom"` for a smooth curve. A value that's a Molang expression, like `"math.cos(query.life_time * 180) * 2.5"`, is an error: do it in the animator with `pose.rotate` or `pose.move`. `deno task check-mods` warns about what the animator does instead, like `sound_effects` and `anim_time_update`. ### Animators The client phase registers an animator for an entity type. Each entity of that type the client has gets its own, and before each frame it's drawn, the animator plays clips and moves bones. A coilhead that bobs as it walks, looks around, and plays `stop` once when it freezes: ```ts import { AnimationState, type ClientContext } from "cubi/client"; export function client(ctx: ClientContext) { const walk = ctx.render.clip("my_mod:coilhead/walk"); const stop = ctx.render.clip("my_mod:coilhead/stop"); ctx.render.register_entity_animator("my_mod:coilhead", (coilhead) => { const frozen = new AnimationState(); return { on_data(field, time) { if (field === "frozen") frozen.animate_when(coilhead.get_client_data("frozen") === true, time); }, pose(pose, time) { if (frozen.started && !frozen.finished(stop, time)) pose.play_state(stop, frozen, time); else pose.play_walk(walk, coilhead, time); pose.look("head"); }, }; }); } ``` - `time` is the entity's age on this client in ticks, with the part of the next one. - `pose.play(clip, seconds, weight)` plays a clip at some point in it. Clips played together add up, and `weight` scales one, so blending from one to another is turning one down while the other goes up. - `pose.play_state(clip, state, time)` plays it from when an `AnimationState` started. An animator keeps one for each clip it starts on its own, and starts and stops it with `start`, `stop` and `animate_when`. - `pose.play_walk(clip, entity, time)` plays it as far through as the entity has walked, as strongly as it's walking. - `pose.rotate`, `pose.move` and `pose.scale` add to a bone on top of the clips, in the clips' units. - `pose.look(bone)` turns a bone to where the entity looks. An animator that throws is removed, with the error in the console, and its entity goes back to the humanoid pose. What the animator knows of the mob's state comes from its client data, which the server side sets: ```ts mob.set_client_data("frozen", true); mob.set_client_data("frozen", undefined); // removes it ``` Client data is saved with the mob and sent to players when it changes. The animator's `on_data` hears about each field as it changes, and about the ones already set when the entity first shows up.