---
url: /pawn/docs/guide/behaviors.md
description: >-
  Behaviors (Hoverable, Clickable, Draggable, Lifetime, Health, motion, SoundOn,
  FlashOn, Burst, your own), presets and entity events.
---

# Behaviors and events

A **behavior** packages one feature (spinning, reacting to the pointer,
playing a sound) as a koota trait with JSON params plus the plugin that
makes it work. It is added to entities like any other trait, and because
its params are plain data, a scene built from behaviors can be saved,
generated or tested headless.

Core has `defineBehavior`, entity events, `closest()` and
the `Hoverable`, `Clickable`, `Draggable`, `Lifetime`, `Health` and motion
(`Velocity`, `Spin`, `Bob`, `FollowPath`) behaviors;
`@pawnjs/tween` has [`TweenOn`](/packages/tween#tweenon). [Presets](#presets)
bundle behaviors, [prefabs](./prefabs.md) describe whole entities (and
[`Spawner`](./prefabs.md#spawner) spawns waves of them), and
[snapshots](/guide/snapshots) save scenes built from them.

## Ready-made behaviors

Hover a shape to tint it, click it to make it jump and spin faster:

```ts
import {
  Clickable,
  Engine,
  Hoverable,
  Position,
  Shape,
  Spin,
} from "@pawnjs/core";
import { TweenOn } from "@pawnjs/tween";

export default function behaviors(canvas: HTMLCanvasElement): Engine {
  canvas.style.cssText = "display:block;width:100%;height:100%";
  const engine = new Engine({
    canvas,
    camera: { position: { y: 1.2, z: 4.5 } },
    background: "#09090b",
    lights: "studio",
  });

  // Hover tints a shape, a click makes it jump and spin faster.
  const kinds = ["box", "sphere", "cylinder"] as const;
  kinds.forEach((kind, i) => {
    const shape = engine.spawn(
      Shape({ kind, color: "#e2e8f0" }),
      Position({ x: (i - 1) * 1.8, y: 0, z: 0 }),
      Spin({ speed: 0.6 }),
      Hoverable({ tint: "#6366f1", amount: 0.7 }),
      Clickable,
      TweenOn({ on: "click", lift: 0.6, duration: 0.25, easing: "quadOut" }),
    );
    let speed = 0.6;
    engine.events.on(shape, "click", () => {
      speed += 2;
      shape.set(Spin, { speed });
    });
  });

  engine.start();
  return engine;
}

```

In short:

```ts
import { Clickable, Hoverable, Hovered, Position, Shape } from "@pawnjs/core";
import { TweenOn } from "@pawnjs/tween";

const button = world.spawn(
  Shape({ kind: "box", color: "#e2e8f0" }),
  Position,
  Hoverable({ tint: "#6366f1" }),
  Clickable,
  TweenOn({ on: "click", scale: 1.1, duration: 0.15 }),
);
engine.events.on(button, "click", () => console.log("clicked"));
world.query(Hovered); // what is hovered now
```

| Behavior | Params | What it does |
|---|---|---|
| `Hoverable` | `tint` (`""`), `amount` (`0.3`), `cursor` (`"pointer"`) | Keeps the `Hovered` tag on the entity while the pointer is over it and emits `pointerenter` and `pointerleave` on it; with a `tint`, adds a `Tint` meanwhile (a `Tint` already there is left alone); sets the canvas cursor. |
| `Clickable` | none | Emits `pointerdown`, `pointerup`, `click`, `doubleclick` and `contextmenu` entity events and keeps the `Pressed` tag while a button pressed on the entity is held. |
| `Draggable` | `plane` (`"view"`, or `"xy"`, `"xz"`, `"yz"`), `enableMove` (`true`) | Drags the entity across a plane through the grabbed point; keeps the `Dragged` tag and emits `dragstart`, `drag` and `dragend` entity events. |
| `Lifetime` | `seconds` (`1`), `shrink` (`0`) | Counts `seconds` down in scaled time; over the last `shrink` seconds scales the entity down to nothing; then emits `expire` and destroys the entity with its children. |
| `Health` | `hp` (`10`), `max` (`10`), `enableDestroy` (`true`) | Hit points, changed with [`damage()`](#health). |
| `Velocity` | `x`, `y`, `z` (`0`) | Moves `Position` by that many units per second, along the parent's axes. |
| `Spin` | `axis` (`"y"`, or `"x"`, `"z"`), `speed` (`1`) | Turns `Rotation` around the entity's own axis, in radians per second. |
| `Bob` | `axis` (`"y"`), `amplitude` (`0.25`), `period` (`2`), `phase` (`0`) | Swings `Position` back and forth along an axis; adds the change each frame, so it combines with other motion. |
| `FollowPath` | `points` (`[]`), `speed` (`1`), `distance` (`0`), `enableLoop` (`false`), `enableFacing` (`true`) | Moves `Position` along the points at `speed`; `distance` is how far it got. At the end it stops and emits `pathend`, or loops. With `enableFacing` it turns around y to face its way (front +z). |
| [`TweenOn`](/packages/tween#tweenon) | `on`, `off`, `scale`, `lift`, `turn`, `duration`, `easing` | Plays a tween when an entity event reaches the entity. |

The pointer behaviors read the engine's [`Pointer`](/guide/input#pointer),
installing it if needed, and count the pointer over a `ChildOf`
descendant's `Visual` as over the entity, so a model built of child
entities reacts as one. `Clickable` emits on the entity that was hit, and
the event bubbles through the clickable entity. `pointerup` goes to the
entity the press was on, wherever the button is released or the press
cancelled; `click` comes only from a press and release on the same
clickable entity, without a drag, and `doubleclick` after the second of two
quick clicks on the same clickable entity. A click with the secondary
button is followed by `contextmenu`, and the browser's own menu does not
open over clickable entities. Every finger presses and clicks, so two
clickable entities tapped together both get their events; hover follows
the primary pointer. `Hoverable` needs the `Pointer`'s hover
picking, which is on unless the pointer was made with
`enableHover: false`.

`Draggable` takes a primary press on the entity (or a child) for itself,
so a [`CameraRig`](/guide/camera) holds still. Once the pointer moves past
the drag threshold the entity gets `Dragged` and `dragstart`, then `drag`
on every move and `dragend` on release; each event carries the `point`
under the pointer on the plane. With `enableMove` the entity's `Position`
follows the pointer (relative to its parent, so children drag too);
`enableMove: false` only emits the events, for code that moves the entity
itself. A press released without a drag is still a click.

```ts
fruit.add(Position, Draggable({ plane: "xy" }));
engine.events.on(fruit, "dragend", () => {
  if (nearMouth(fruit)) eat(fruit);
});
```

Entering and leaving are koota's query modifiers, and React reads the tags
with `useHas`:

```ts
const Entered = createAdded();
for (const entity of world.query(Entered(Hovered))) playSound();

const hovered = useHas(entity, Hovered);
```

### Reduced motion

Only your app knows which motion is decoration (a spinning logo) and
which carries meaning (`FollowPath` showing a flow), so the motion
behaviors have no global switch for `prefers-reduced-motion`. Leave the
decorative ones out while the user asks for less motion, and follow the
setting when it changes:

```ts
import { Spin } from "@pawnjs/core";

const reduce = matchMedia("(prefers-reduced-motion: reduce)");
const follow = () => {
  if (reduce.matches) logo.remove(Spin);
  else logo.add(Spin({ speed: 0.5 }));
};
follow();
reduce.addEventListener("change", follow);
```

`Bob` and a decorative `FollowPath` go the same way; a `FollowPath`
that shows a flow can stay, slower (`speed`). `engine.clock.timeScale`
slows everything at once, the motion that
matters too (see [Clock](./engine.md#clock)).

## Defining a behavior

```ts
import { defineBehavior, Rotation } from "@pawnjs/core";

export const Wobble = defineBehavior({
  name: "wobble",
  params: {
    speed: { default: 1, min: 0, description: "Wobbles per second" },
    axis: { default: "y", enum: ["x", "y", "z"] },
  },
  install(engine, { trait }) {
    return engine.addSystem(({ world, delta }) => {
      world
        .query(trait, Rotation)
        .select(Rotation)
        .updateEach(([rotation], entity) => {
          const { speed } = entity.get(trait)!;
          // ... tilt `rotation` back and forth, speed times a second
        });
    });
  },
});

entity.add(Wobble({ speed: 0.5 })); // a normal koota trait
entity.set(Wobble, { speed: 2 });   // change params with set
```

`defineBehavior` returns a koota trait, used like any other: its fields
are the params, with their defaults. The engine installs what makes it
work the first time an entity gets it. The trait also carries:

| Member | Meaning |
|---|---|
| `name` | Stable kebab-case id, used by presets and saved scenes. |
| `plugin` | Runs `install` once per engine; its name is `"@pawnjs/behavior/<name>"`. `engine.use(Wobble.plugin)` installs it before any entity has the behavior. |
| `params` | The param specs as defined: `default`, `min`, `max`, `enum`, `description`, `schema`. |

Params are numbers, strings and booleans. A list or object param takes a
factory default (`points: { default: () => [] }`), so each entity gets its
own; change it with `entity.set`, since changes inside it are not seen.
`defineBehavior` throws on a name that is not kebab-case and on a default
that is not one of these, or not in its `enum`. A behavior without params
is a tag.

The name is the behavior's id on an engine, so two behaviors may not share
one: the second is not added to entities, and the engine warns once, while
`applyPreset` and `engine.use(behavior.plugin)` throw for it. A hot reload
that defines a behavior again does this too, so reload the page.
Core's behaviors take theirs (`spin`, `bob`, `velocity`, `follow-path`,
`hoverable`, `clickable`, `draggable`, `health`, `lifetime`, `spawner`,
`sound-on`, `flash-on`, `burst`) and `@pawnjs/tween` takes `tween-on`;
name your own otherwise.

Give a list or object param a `schema`, in a subset of JSON Schema, and
its values are checked too, by presets, prefabs, saved scenes and
`@pawnjs/json-render`; `toJSONSchema` passes it on:

```ts
export const Patrol = defineBehavior({
  name: "patrol",
  install: () => undefined, // its system, as above
  params: {
    points: {
      default: (): Vec3Like[] => [],
      schema: {
        type: "array",
        items: {
          type: "object",
          properties: { x: { type: "number" }, z: { type: "number" } },
          required: ["x", "z"],
        },
      },
    },
  },
});
```

It takes `type`, `properties`, `required`, `additionalProperties`,
`items`, `minItems`, `maxItems`, `minimum`, `maximum`, `enum`, `const`,
`anyOf` and `description`; the type is `ValueSchema`.
`validateValue(schema, value)` checks one value against it, and
`valueSchemaOf(spec)` gives any param's spec as one (a plain param's type,
`enum`, `min` and `max`), so every check reads params the same way.

A behavior that reacts to an entity event chosen as data, like `SoundOn`
or `TweenOn`, installs with `listenOn`: it calls the handler of each
param whenever the event that param names reaches an entity with the
behavior, follows `entity.set` changes and stops on removal. An empty
param listens to nothing.

```ts
export const Toggle = defineBehavior({
  name: "toggle",
  params: {
    on: { default: "click", description: "Event that switches it on." },
    off: { default: "", description: "Event that switches it off." },
  },
  install: (engine, { trait }) =>
    listenOn(engine, trait, {
      on: (entity) => console.log("on", entity),
      off: (entity, event) => console.log("off by", event.type),
    }),
});
```

For typed code around params, core exports `ParamSpec` (one param's spec),
`ValueSchema` (the values a param takes),
`ParamSpecs` (a record of them), `ParamDefault` and `ParamValue` (the value
a spec describes), and `BehaviorData<P>`, the trait value of a behavior with
params `P`.

## Presets

A **preset** is a named list of behaviors with their params, so a whole
feature is applied to an entity in one call:

```ts
import {
  applyPreset,
  Clickable,
  definePreset,
  Hoverable,
  removePreset,
} from "@pawnjs/core";
import { TweenOn } from "@pawnjs/tween";

export const Button3D = definePreset({
  name: "button3d",
  behaviors: [
    [Hoverable, { tint: "#6366f1" }],
    Clickable,
    [TweenOn, { on: "click", scale: 1.1, duration: 0.15 }],
  ],
});

applyPreset(engine, entity, Button3D);
applyPreset(engine, other, Button3D, { hoverable: { tint: "#f59e0b" } });
removePreset(other, Button3D);
```

`applyPreset` installs each behavior's plugin the engine lacks, then adds
each behavior's trait with the preset's params and the overrides, keyed by
behavior name. An entity that already has a trait gets those params set,
and its other params keep their values; lists and objects in params are
copied per entity. `removePreset` removes every behavior the preset lists,
also one the entity had before or got from another preset. Presets do not
nest; list the behaviors instead.

Params are checked against each behavior's specs: `definePreset` and
`applyPreset` throw on an unknown behavior or param, a value of the wrong
type, or one outside its `min`, `max` or `enum`, and nothing is applied.
TypeScript catches the first two already: `applyPreset`'s overrides are
typed by the preset's behaviors.
`validateParams(behavior, values)` runs the same check and returns the
problems as messages:

```ts
validateParams(Hoverable, { amount: 2 });
// ["hoverable.amount: 2 is above the maximum 1."]
```

## Feedback: sound, flash, burst

Three behaviors answer an entity event with feedback, so a hit or a
pickup feels like one without code. Each has an `on` param naming the
event, and follows changes to it.

```ts
import { Burst, FlashOn, SoundOn } from "@pawnjs/core";

enemy.add(
  FlashOn({ on: "damage", color: "#ffffff", amount: 0.85, seconds: 0.12 }),
  Burst({ on: "died", count: 16, speed: 2.5, color: "#f43f5e" }),
  SoundOn({ on: "died", frequency: 660, to: 990, wave: "triangle", variation: 0.1 }),
);
```

* `SoundOn` plays an audio file (`url`) or, without one, a synthesized
  tone (`frequency`, `to` for a slide, `duration`, `wave`), at `volume`,
  with a random pitch change of up to `variation` (from `engine.random`). It plays through
  [`Sound`](./sound.md).
* `FlashOn` tints the entity with `color` by `amount` for `seconds` of
  scaled time. A flash during a flash starts the time again, and a `Tint`
  the entity had before comes back after.
* `Burst` throws `count` small spheres from the entity's world position at
  `speed`, each `size` wide in `color`, living `seconds` and shrinking at
  the end; `flatten` goes from a sphere (0) to a flat ring (1). The
  particles are plain entities (`Velocity`, `Lifetime`, `Shape`) in the
  entity's scope. `burst(engine, point, options)` throws one from code.

An entity has each behavior once, so one `SoundOn` per entity; play other
sounds from listeners with `engine.plugin(Sound)`.

## Health

`Health` holds hit points; `damage(engine, entity, amount)` takes them (a
negative amount heals, up to `max`) and returns what is left:

```ts
import { damage, Health } from "@pawnjs/core";

enemy.add(Health({ hp: 8, max: 8 }));
engine.events.on(enemy, "damage", ({ amount }) => flash(enemy));
engine.events.on(enemy, "died", () => addGold(1));
damage(engine, enemy, 3); // 5
```

It emits a `damage` entity event with the hit points taken, and when they
reach 0 a `died` event, then destroys the entity with its children unless
`enableDestroy` is off or a listener healed it. Damage to an entity without
`Health`, or already at 0, does nothing.

## Entity events

`engine.events` carries instant events on entities, such as `click`. An
event goes to the entity's listeners, then bubbles up `ChildOf`, so a
click on a wheel reaches the car:

```ts
const off = engine.events.on(car, "click", (event) => {
  event.target;         // the wheel
  event.currentTarget;  // the car
  event.stopPropagation();
});
engine.events.emit(wheel, "click", { button: 0, point: undefined });
off();
```

Emitting runs the listeners at once. Emit after iterating a query rather
than inside it, since listeners may add or remove traits. Core defines
`click`, `doubleclick`, `contextmenu`, `pointerdown`, `pointerup`,
`pointerenter`, `pointerleave`, `dragstart`, `drag`,
`dragend`, `damage` and `died` (from `damage()`), `expire` (from
`Lifetime`), `pathend` (from `FollowPath`) and `wavestart`, `waveend`,
`spawn` and `spawnerend` (from [`Spawner`](./prefabs.md#spawner)); add your own with declaration
merging:

```ts
declare module "@pawnjs/core" {
  interface EntityEventMap {
    alarm: { level: number };
  }
}
```

Lasting state, such as being hovered, is a trait that systems and UI
query, not an event.

`engine.events` is an `EntityEvents`. A plain `new EntityEvents()` works
without an engine, for tests of code that only emits and listens. Listeners
are typed as `EntityEvent<K>`: the payload plus `type`, `target`,
`currentTarget` and `stopPropagation()`.

## Finding the entity that carries a behavior

Picking returns the entity whose `Visual` was hit, often a child of the
entity that has the behavior. `closest(entity, trait)` returns the entity
itself or its nearest ancestor up `ChildOf` with the trait:

```ts
import { closest, Pointer, Spin } from "@pawnjs/core";

engine.plugin(Pointer).on("click", ({ entity }) => {
  const spinning = closest(entity, Spin);
  if (spinning) spinning.set(Spin, { speed: 0 });
});
```

`Hoverable` and `Clickable` find their entity this way.
