habitat

A robot who lives on a web page. He walks, jumps, gets picked up and thrown, and when you leave him alone long enough he goes off and finds something to do.

Source · Seen in the wild · No dependencies

walk · space jump · drag him · click to say hi

How he works

He is not a sprite sheet. He is a jointed SVG rig — two segments per limb, so knees and elbows actually bend — and every frame a state machine writes joint angles into a pose object which is then applied to the DOM.

The life comes from four cheap things. Gravity and ground contact. A damped spring on the antenna, so it lags going into a move and overshoots coming out of one. Squash and stretch on landing, scaled by impact speed. And a pupil that chases your cursor, with a blink on a random timer. That is most of the trick: none of it is expensive, and all of it is the difference between a shape being moved around and a thing that seems to be moving itself.

Using him

import { createHabitat } from "./src/habitat.js";

const habitat = createHabitat(document.querySelector("#habitat"));

habitat.command("cook");   // or sleep, ride, climb, service, idle
habitat.destroy();         // takes its listeners and its rAF loop with it

Give the host element a size and he fills it. He brings his own SVG, his own gradients, and his own colors, so nothing is required of the page around him. Pass theme to repaint him, activities to give him new things to do, or autonomy: false if you would rather he only did what he is told.

Adding something for him to do

An activity is a pose function and a mark to stand on. While one runs it owns his transform outright, which is what keeps each one self-contained — this is the whole of "he waves at the wall":

wave: {
  scene: "workshop", mark: 500, duration: 8, status: "waving",
  pose(p, t) {
    p.x = 500;
    p.armF = -150 + Math.sin(t * 9) * 22;
    p.elbowF = 26;
    p.headR = -5;
  },
}

Angles are degrees from hanging straight down. A limb at angle t points along (−sin t, cos t). Once he is rotated −90° to lie down that becomes (cos t, sin t) on stage, so 0 runs toward his feet and −90 is straight up. Getting that backwards is how you put a robot's arm through the floor, which is a thing that happened here more than once.