Play Strawberry Docs
Scripts

Animated characters

Bring a Blockbench model with bones and animations and get a mob that walks, plays its animations, takes damage and has a boss bar of its own look.

How it works

A player on a vanilla Java client cannot be sent a new mob shape. An animated character is built from what the game already draws: each moving part of your model (a head, an arm, a leg) is an item display that shows that part's model from the server's pack. The parts ride an invisible mob that carries the hitbox, the health, the movement and the attack, so the character walks, is hit and dies like a mob.

The custom-models script does the work for you. You give it the model once, when your script loads; it puts the parts into the server's pack, plays the right animation for what the mob is doing (standing, walking, attacking, hurt, dying) and removes the parts when the mob goes. Your script never moves a part itself.

  • Walking costs nothing extra: the parts ride the mob, so the client moves them with it.
  • An animation is a few keyframes a second, one bundle for all the parts of a mob, and the client glides between them, so it looks smooth without a packet every tick.
  • Only players who can see the mob get its keyframes. A mob nobody sees sends nothing.

The example on this page is a complete script: a walker with a head, two arms and two legs that looks around, walks, flinches when it is hit and falls over when it dies, with a green boss bar of its own look that shows its health.

The model

Make the model in Blockbench as a Generic Model project and keep the texture inside the file (.bbmodel). Put every part that moves into its own group (bone), and add the animations on the Animate tab.

  • A group that an animation moves becomes one part. A group that never moves is joined to the part above it, so a still hat on a moving head costs nothing more.
  • Read: cubes (with per-face UV, rotation, inflate), embedded PNG textures, rotation, position and scale keyframes with linear, Catmull-Rom or step curves, and loop modes (loop, once, hold).
  • Refused, with the reason: meshes and other elements that are no cube, Molang expressions in keyframes, bezier keyframes, inverse kinematics, textures with animation frames, textures that are not inside the file. Sound, particle and timeline keyframes are left out.
  • A group with moving groups under it may only be scaled the same on all three axes.

Limits, checked when your script registers the model and the mob: a file of 4 MiB, 4 textures, 512 cubes, 128 groups, 24 drawn parts per character and 16 per mob, 32 animations, 120 seconds per animation. For the mob, an idle or walk loop lasts at most 20 seconds, an attack or hurt animation 3 seconds, a death animation 2 seconds. Over a limit the request is refused with the number that was too high, and nothing is kept.

Talk to custom-models

Every request is a script message to custom-models (see Inter-script communication). A request is some text lines; when it carries files, an empty line follows, then each file as its path and length on one line and its bytes. The answer starts with ok and its fields separated by tabs, or it is the reason it was refused (invalid:, unknown:, limit:, unavailable:).

rust
/// A request with files: the settings, an empty line, then each file as `<path> <length>` and its
/// bytes.
fn with_files(settings: &str, files: &[(&str, &[u8])]) -> Vec<u8> {
    let mut out = settings.as_bytes().to_vec();
    out.push(b'\n');
    for (path, bytes) in files {
        out.extend_from_slice(format!("{path} {}\n", bytes.len()).as_bytes());
        out.extend_from_slice(bytes);
    }
    out
}
rust
/// Sends one request to custom-models: the fields after `ok`, or the reason it was refused.
fn ask(request: &[u8]) -> std::result::Result<Vec<String>, String> {
    match send_ipc_message("custom-models", request) {
        Ok(Ok(answer)) => {
            let text = String::from_utf8_lossy(&answer).into_owned();
            let mut fields = text.split('\t').map(str::to_owned);
            match fields.next().as_deref() {
                Some("ok") => Ok(fields.collect()),
                _ => Err(text),
            }
        }
        Ok(Err(refused)) => Err(refused),
        Err(()) => Err("custom-models is not on this server".to_owned()),
    }
}

Declare custom-models in your script's dependencies, so your script loads after it. The strawberry-tools crate builds these requests for you (see Play Strawberry's tools).

Register the character and the mob

In on_load, register the character with its Blockbench file, a line for its name in four languages, and the mob. Each answer ends with ready once players get the parts in the server's pack, or pending until then.

rust
// The character, its name, the mob that carries it, and the boss bar's pictures. Each
// answer says `ready` once players get it in the server's pack.
ask(&with_files(
    "character walker\n",
    &[("model.bbmodel", MODEL)],
))?;
ask(&with_files(
    "line walker_name\ntext.en=Walker\ntext.fr=Marcheur\ntext.es=Caminante\ntext.tr=Yürüyen\n",
    &[],
))?;
let mob = ask(MOB.as_bytes())?;
state().mob = mob.first().cloned();
ask(&with_files(
    "fonts\n",
    &[
        ("sprite/boss_bar/green_background.png", BAR_BACKGROUND),
        ("sprite/boss_bar/green_progress.png", BAR_PROGRESS),
    ],
))?;

The mob request names the character and its settings:

rust
/// The mob: which character, its carrier, its health and attributes, and its animation for each
/// state. `name` is the line registered before it.
const MOB: &str = "mob walker
character=walker
carrier=zombie
health=40
speed=0.2
attack=3
anim.idle=idle
anim.walk=walk
anim.hurt=hurt
anim.death=death
name=walker_name
";
  • carrier: the invisible mob under the model, one of husk (the default), zombie, skeleton, stray, spider, cave_spider, cow, pig, wolf, polar_bear, iron_golem, ravager, ghast. Its hitbox stays the carrier's.
  • health (1 to 1024), speed (0.01 to 2), attack (0 to 100), armor (0 to 30), knockback_resistance (0 to 1), follow_range (1 to 64): left out, the carrier's own.
  • scale (0.25 to 8) and lift (-4 to 4 blocks): the model's size and height on its carrier.
  • anim.idle, anim.walk, anim.attack, anim.hurt, anim.death: one of the character's animations for each state. You may leave states out; the example has no attack animation.
  • attack.hit: the seconds into the attack animation at which the hit lands (at most one second, within the animation).
  • sound.ambient, sound.hurt, sound.death, sound.step, sound.attack: sounds you registered, by name.
  • name: one of your lines, shown over the mob in each player's language; name.height places it.

The mob's drops are your own drop rules; the carrier's vanilla loot never drops.

Put one in the world

mob-spawn <mob id> <world> <x> <y> <z> <yaw> puts one where you say and answers its UUID. The mob id is the first field of the mob's answer (<your script>.walker). An admin can also place one with /models spawn <mob id> on the block he looks at.

rust
struct Call;

impl CommandHandler for Call {
    fn handle(
        &self,
        sender: CommandSender,
        _server: Server,
        _args: ConsumedArgs,
    ) -> Result<i32, CommandError> {
        let Some(player) = sender.as_player() else {
            sender.send_message(TextComponent::text(text("en", "player")));
            return Ok(0);
        };
        let locale = player.get_locale();
        let Some(mob) = state().mob.clone() else {
            sender.send_message(TextComponent::text(text(&locale, "refused")));
            return Ok(0);
        };
        let (x, y, z) = player.get_position();
        let world = player.get_world().get_name();
        let request = format!(
            "mob-spawn {mob} {world} {x:.3} {y:.3} {z:.3} {:.1}",
            player.get_yaw()
        );
        match ask(request.as_bytes()) {
            Ok(fields) => {
                let Some(carrier) = fields.first().cloned() else {
                    return Ok(0);
                };
                let bar = BossBar::new(
                    title(&locale, MAX_HEALTH),
                    BossBarColor::Green,
                    BossBarDivision::NoDivision,
                );
                bar.set_health(1.0);
                bar.add_player(player);
                state().bars.insert(
                    carrier,
                    Bar {
                        bar,
                        locale,
                        entity_id: None,
                    },
                );
                Ok(1)
            }
            Err(reason) => {
                sender.send_message(TextComponent::text(&format!(
                    "{} {reason}",
                    text(&locale, "refused")
                )));
                Ok(0)
            }
        }
    }
}

A script has at most 32 of its animated mobs in the world at once, and a server 64; a spawn over that is refused with the reason, never queued. A script registers at most 64 mobs. The mob is saved with the world; its parts are built again when its chunk loads. When your script is unloaded, its mobs stand still where they are and cost nothing until it is loaded again.

A boss bar with its own look

A boss bar's look is two pictures of the game, boss_bar/<colour>_background and boss_bar/<colour>_progress, each 182 by 5 pixels. Send your own two in a fonts request as sprite/boss_bar/<colour>_background.png and sprite/boss_bar/<colour>_progress.png (the example draws a gold frame on dark red, filled with green), then make your bars in that colour. The server owner approves these pictures in the server panel, as every file that changes the game's own.

The pictures replace that colour for every boss bar on the server, so pick one nothing else uses: the ender dragon's bar is pink, the wither's purple, a raid's red, a bar made with /bossbar white, and Play Strawberry's interface script draws its HUD with yellow. The example uses green.

The example keeps the bar's text and fill up to date: when the walker is hit it reads the health on the next tick and shows it.

rust
/// Reads the walker's health once the damage is applied, on the next tick, and shows it.
fn show_health(server: &Server, entity_id: i32) {
    let Some(entity) = server.get_entity_by_id(entity_id) else {
        return;
    };
    let Some(living) = entity.as_living() else {
        return;
    };
    let key = uuid::to_string(entity.get_uuid()).to_ascii_lowercase();
    let health = living.get_health();
    if let Some(bar) = state().bars.get(&key) {
        bar.bar.set_health((health / MAX_HEALTH).clamp(0.0, 1.0));
        bar.bar.set_title(title(&bar.locale, health));
    }
}

For a larger frame, a picture above the bar or numbers drawn your way, put the pictures into a font and the characters into the bar's title (see Resource packs, "Fonts of your own").

Bedrock players

Animated characters are drawn for Java players; Bedrock players do not see the model. Give an animated mob a name: Bedrock players see the name over it.

Try it

Build the example, load it on your developer server next to custom-models, approve the boss bar pictures in the panel, and type /walker. The walker looks around, walks after you, flinches when you hit it with the bar going down, and falls over when it dies.

On this page