Skip to main content

Enemies and AI

Enemies are events with a BattleAi. The AI controller manages behavior only; stats come from the standard RPGJS API.

Enemy types

Enemy types affect behavior, not stats:

Attack patterns

Enemy attack cadence

Enemy attacks separate preparation (startupMs), the active phase (activeMs) and recovery (recoveryMs). The enemy stops moving and keeps its attack direction during these phases. The telegraph runs during preparation; the attack animation then plays one complete cycle over active + recovery time. The client receives this duration as animationDefaults.durationMs; damage and action locks remain authoritative on the server, in both RPG and MMORPG. A new attack waits for the global attackCooldown, the selected profile’s cooldownMs, and its complete phase duration. Combo strikes wait for their profile’s duration and cooldown before continuing; the global cooldown separates attack sequences. Profile overrides allow faster or slower enemies without depending on sprite names or image dimensions. Default timings, in milliseconds: Override these values through BattleAi options, for example attackProfiles: { melee: { startupMs: 180, recoveryMs: 250, cooldownMs: 800 } }. Without a client animation mapping, combat timings and damage still work. Remote characters use the synchronized walk/stand state; local players retain input-driven locomotion while temporary attack animations finish. When attackPatterns is explicitly configured, archetype decisions choose only from that list. If an archetype suggests no permitted pattern, the configured list is retained. This prevents generic aggressive behavior from introducing a combo or dash that the enemy designer disabled. The elapsed-time playback correction also requires the companion CanvasEngine sprite scheduler fix (raw and reset-envelope ticks). Publish that patch and update the consumer’s CanvasEngine lockfile alongside these RPGJS changes.

AI configuration

All AI options are optional:
Per-enemy animations override the global provideActionBattle() animations. Use a string for a simple animation name, an object to temporarily switch graphics, or a resolver function for data-driven events. Return null or undefined from a resolver to skip the animation. attackProfiles lets enemies telegraph attacks with startupMs, keep hitboxes active for activeMs, and apply hit reactions. poise controls interruption: an incoming hit only stuns the enemy when its reaction.staggerPower is greater than or equal to the enemy’s poise. rewards are awarded once to the player who lands the killing blow. On defeat, Action Battle calls event.remove({ reason: "defeated", transition }). The server removes collision immediately while clients keep the sprite long enough to play its Studio die animation and a configurable CanvasEngine death effect. Use presentation.death to tune the effect, scale, shake, and duration, or set it to false for immediate removal. The legacy onDefeated(event, attacker) signature remains supported for two-argument callbacks. When combat spritesheets come from RPGJS Studio media fields, convert the media ids with createStudioActionBattleAnimations(). Studio-generated combat spritesheets are played with setGraphicAnimation("attack", graphic, 1) by default:
Without arguments, the helper reads the Studio project animations attached to the player at runtime by provideStudioGame(). You can still pass a static object when you want to override the media ids manually. Animation values may be media ids or media objects returned by the Studio game API. Studio four-direction attack spritesheets play in 350ms by default so their visual timing matches the default Adventure attack profile without changing the walk animation speed. A media record may override this client-side presentation with metadata.attackDurationMs; gameplay startup, active, and recovery windows remain server-authoritative and independent. For Studio enemies, the runtime reads enemy.animations automatically when an enemy is created from the Studio database. The supported Studio fields are attack, hurt, die, castSpell, guard, parry, and stagger; castSkill is also accepted when you configure action-battle directly. stagger falls back to the Studio hurt animation. These values are resolved on the server and sent to the client as plain animation data, so media IDs remain usable without transferring resolver functions. Global animation resolvers are also evaluated on the server for player skill casts that do not supply animation overrides. This uses the caster’s configured Studio animations in both standalone and MMORPG games.

Composable AI behaviors

Action Battle has three AI layers. They all run on the server and end in the same authoritative runtime for movement, attacks, skills, cooldowns, hit reactions, and rewards.
  • Presets are the fastest path for common enemies.
  • Simplified behaviors are readable rule lists that return intentions.
  • Behavior trees are the advanced API for bosses and custom enemy logic.

Presets

Use a built-in preset and override only what changes:
Built-in presets are aggressive, defensive, ranged, tank, and berserker. A preset is only behavior configuration. Stats still come from the event itself. Register project presets through provideActionBattle():
Then instantiate enemies from the preset:
Presets are composable. A project preset can extend a built-in preset or another project preset with preset: "name". Local options passed to new BattleAi() override the preset values.

Simplified behaviors

Use simpleBehavior when you want expressive rules without writing a full behavior tree. Each rule checks a condition and returns an intent:
Common condition helpers: Common intention helpers:

Behavior trees

Use behaviorTree when you need explicit tree control. A tree node returns success, failure, or running, optionally with an intent or decision.
The built-in tree helpers are intentionally small:

Dynamic behavior and memory

Intent functions receive the AI context and can use memory for per-enemy state:
The context includes:

Boss phases and delayed sequences

Phase helpers keep scripted behavior in the existing behavior-tree runtime. Their state is stored per AI instance in memory, so a preset can safely be shared by several enemies:
phase(key, hpRatio, action) completes once after HP falls below the ratio. once(key, action) provides the same one-time behavior without an HP condition. cooldown(key, ms, action) starts its cooldown only after the wrapped action succeeds. sequenceWithDelay(key, steps) advances across AI ticks, and wait(ms) uses the authoritative server clock without creating client-owned gameplay timers. Use run(callback) when project logic is local to the tree. For reusable or module-provided behavior, register a named action:
callAction() returns failure when its name is not registered, allowing a selector to continue to a fallback branch.

Server-driven AI visuals

visual() sends a JSON-shaped cue through the existing Action Battle client visual packet. The server decides when it happens; the client handler only renders it:
Unknown visual kinds are ignored. Keep cue payloads serializable and use once() or cooldown() around cues selected by a tree branch so they are not sent on every 100 ms AI tick. Visual handlers must never apply damage, change stats, select targets, or otherwise own gameplay state.

Movement and server actions

The advanced intent helpers are thin wrappers over the controlled event: Teleport helpers deliberately use the normal RPGJS teleport primitive and do not search for a collision-free position. Projects that need safe placement should resolve it in run() or a registered action before calling teleportTo().

Sample project

samples/sample-dev contains four AI demo enemies on center-map:
  • Preset Rusher uses a named preset.
  • Simple Kiter uses simpleBehavior and distance control.
  • Tree Elite uses a direct behaviorTree.
  • Phase Boss uses delayed phases, generic visuals, speed changes, teleportation, and a registered action.

Debug enemy decisions

Decision tracing is disabled by default. Enable it on the authoritative server and optionally filter one enemy or a set of categories:
decision logs include the distance, global cooldown, evaluated skills, effective ranges, rejection reasons, and the selected attack or repositioning request. Common rejection reasons are cooldown, insufficientSp, outOfRange, invalidTarget, maskMiss, and notUseful. For increasing levels of control, start with learned skills only, add attackSkill for an explicit priority, use defineActionBattleAiPreset() for reusable typed defaults, then use behaviorKey or a behavior tree for fully custom decisions.

Examples

Basic enemy

Mage with skills

Patrol guard