Action Battle System
Advanced real-time action combat AI system for RPGJS. The AI controller manages behavior only. All stats, HP, SP, skills, items, classes, and states are configured with the standard RPGJS API.Features
- State machine AI with
Idle,Alert,Combat,Flee, andStunned - Multiple enemy types:
Aggressive,Defensive,Ranged,Tank,Berserker - Attack patterns:
Melee,Combo,Charged,Zone,DashAttack - Skill support with standard RPGJS skills
- Dodge and counter-attack behaviors
- Group behavior and waypoint patrols
- Knockback driven by weapon configuration
- Hook system with
onBeforeHitandonAfterHit
Installation
Quick Start
EventDefinition.
The returned object only describes the event behavior. Placement data such as id, x, and y
still belongs to the outer maps[].events wrapper.
Factions and targets
BattleAi can target players, other battle events, every combat entity, hostile
factions, or an explicit list of factions.
players: target all players.events: target action-battle events.all: target players and action-battle events.hostile: target entities with a different faction.["guards", "bandits"]: target only these factions.(context) => boolean: fully custom target rule.
Enable the module
Register the module on the server:animations is optional. If you omit it, attacks keep using the default
attack animation and no extra hurt, death, or skill-cast animation is played.
Player attacks lock movement for 350ms by default. This gives an A-RPG feel
where the hero performs the attack in place before moving again.
lockMovement to false if you want players to keep moving while
attacking. The client stops local predicted movement as soon as the action
input is pressed and shows a short slash preview by default. Disable
showPreview when you provide your own client-side attack effect.
Recommended composable DX
New action-battle configuration is grouped by responsibility:combatowns gameplay rules: player attack profile, damage, knockback, and hit hooks.visualowns temporary combat feedback: sprite animations, flashes, damage text, CanvasEngine effects, and previews.uiowns client components: action bar, targeting overlay, attack preview, and custom GUI or sprite components.aiowns reusable AI behavior functions.skills.targetingowns action targeting metadata for skills.
visual preset on the server and client when your project splits
configuration by runtime. The server still decides when authoritative hit, hurt,
skill, and enemy attack feedback should happen, but it sends one compact
action-battle client visual event. The client resolves that visual locally and
groups the flash, hit text, sound, component animation, or sprite animation.
This keeps gameplay authority on the server while avoiding several visual
packets for one combat moment. The client also triggers local input feedback
such as the attack preview.
@rpgjs/action-battle.
Visual composition
createActionBattleVisual() accepts a preset or a map of visual parts. A visual
part is a function receiving the current combat context and helper methods.
action-battle-hit-fx. You can also call any component animation registered by
your own client modules with fx.component(entity, id, params).
Action-battle visual composition runs through the general
Client Visuals mechanism for server-triggered combat
feedback. Use direct server visual APIs for isolated one-off effects, and use
visual here when you want action-battle to group combat presentation on the
client.
The legacy animations option still works for sprite animation names and
temporary graphics. New orchestration should go through visual, while
animations remains useful as the data source used by
fx.graphic(entity, "attack"), fx.graphic(entity, "hurt"), and
fx.graphic(entity, "castSkill").
Composable UI
The UI is client-owned. Keep the defaults, disable them with booleans, or replace each component.Compatibility
The legacyattack, systems.combat, systems.ai, and skills.getTargeting
options are still supported. New code should prefer combat, ai, and
skills.targeting so each part of the action-battle module stays independently
replaceable.
Attack profile model
Useattack.profile to describe the timing model of a player attack in one
typed object. A profile separates the attack into startup, active, and recovery
phases so combat systems can share the same vocabulary.
350ms. The player attack runtime uses
startupMs before creating the hitbox, activeMs to keep the hitbox active,
and totalDurationMs for movement and direction locks.
| Field | Purpose |
|---|---|
id | Stable name for this attack profile. |
startupMs | Wind-up time before the attack should become active. |
activeMs | Duration of the intended hit window. |
recoveryMs | Time after the active window before the action fully recovers. |
cooldownMs | Minimum delay before the same profile should be reused. |
movementLock | Whether the attack should lock movement. |
directionLock | Whether the attack should lock facing direction. |
animationKey | Animation key from animations, usually attack. |
hitPolicy | oncePerTarget blocks duplicate hits during one attack; allowRepeatHits allows repeated hits. |
reaction.invincibilityMs | Temporary invincibility after this hit connects. |
reaction.hitstunMs | Stun duration requested by this hit. |
reaction.staggerPower | Stagger value compared against enemy poise. |
hitboxes | Optional hitbox overrides for this profile. |
Skill and weapon actions
Skills and weapons can define anaction block for action-battle selection,
while their effect stays automatic by default.
BattleAi uses this block when it casts attackSkill or attacks with an
equipped weapon. Player action-bar skills and configured equipped weapons use
the same executor, so onUse receives the same context in both cases.
onUse, action-battle applies the standard RPGJS skill effect:
SP cost, hit rate, states, and damage formulas. For weapons, the default effect
is a physical hit using the equipped weapon stats and action-battle hit hooks.
action.target can be "enemy", "ally", "self", or "any"; enemy
resolution uses the attacker’s action-battle faction and targets selector.
Projectile direction uses the same generic projectile options as
map.projectiles.emit(), including spreadDegrees and accuracy.
Use onUse(user, target, ctx) only when the action needs custom logic:
ctx.defaultEffect():
Plugin-first extension points
Action battle is structured as replaceable systems. You can keep the default Zelda-like sword attack and only replace the pieces your game needs.@rpgjs/action-battle/server:
ActionBattleCombatSystem, ActionBattleAiBehavior,
ActionBattleHitHooks, and ActionBattleHitResult.
For data-driven enemies, use createActionEnemy():
BattleAi, the server lets the
event handle onAction and does not create the combat hitbox. Enemy events
with BattleAi still trigger the A-RPG attack.
Configure stats with the standard RPGJS API
The AI uses the event’s existing data.Health and resources
Parameters
Skills
Items and equipment
Classes
States
AI configuration
All AI options are optional: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 only sends that removal context; client modules decide how to render it
with sprite.onBeforeRemove, for example by awaiting a death animation, playing
a sound, or showing a particle effect before the sprite disappears. 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:
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.
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, and castSpell. castSkill is also accepted when you
configure action-battle directly.
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:aggressive, defensive, ranged, tank, and
berserker. A preset is only behavior configuration. Stats still come from the
event itself.
Register project presets through provideActionBattle():
preset: "name". Local options passed to new BattleAi()
override the preset values.
Simplified behaviors
UsesimpleBehavior when you want expressive rules without writing a full
behavior tree. Each rule checks a condition and returns an intent:
| Helper | Meaning |
|---|---|
ifHpBelow(ratio, intent) | Run an intent when enemy HP is below a ratio. |
ifTargetVisible(intent) | Run an intent when the AI currently has a target. |
ifTargetInRange(intent, range?) | Run an intent when the target is within a range. |
ifDistanceLessThan(distance, intent) | Run an intent when the target is too close. |
| Helper | Runtime behavior |
|---|---|
chase() / moveToTarget() | Move toward the current target. |
flee() / fleeFromTarget() | Flee from the current target. |
keepDistance(distance, tolerance?) | Retreat or approach until the target is near the desired distance. |
useAttack(pattern?) | Use a configured attack pattern when cooldown and range allow it. |
useSkill(skill) | Cast a skill against the current target when cooldown and range allow it. |
faceTarget() | Face the current target. |
patrol() | Continue the configured patrol route. |
idle() | Stop movement for this AI tick. |
Behavior trees
UsebehaviorTree when you need explicit tree control. A tree node returns
success, failure, or running, optionally with an intent or decision.
| Helper | Purpose |
|---|---|
selector([...]) | Try children in order and return the first non-failure result. |
sequence([...]) | Run children in order and fail as soon as one child fails. |
condition(predicate) | Convert a predicate into a tree node. |
action(intent) | Convert an intent into a tree action. |
decision(fnOrObject) | Return low-level AI decisions such as mode, cooldowns, or attack patterns. |
defineAiTree(input) | Wrap a tree function or node. |
defineAiBehavior({ when, otherwise }) | Compile simplified behavior rules to a tree. |
Dynamic behavior and memory
Intent functions receive the AI context and can usememory for per-enemy
state:
| Field | Description |
|---|---|
event / self.event | The controlled RpgEvent. |
target | The current RpgPlayer target, or null. |
targetInfo | Target distance, visibility, and attack-range status. |
state / self.state | Current AiState. |
enemyType / self.enemyType | Current EnemyType. |
hpPercent / self.hpPercent | Current HP ratio, or null if max HP is unavailable. |
memory | Mutable per-AI storage for custom behavior state. |
Sample project
samples/sample-dev contains three AI demo enemies on center-map:
Preset Rusheruses a named preset.Simple KiterusessimpleBehaviorand distance control.Tree Eliteuses a directbehaviorTree.
Enemy types
Enemy types affect behavior, not stats:| Type | Attack Speed | Dodge | Behavior |
|---|---|---|---|
| Aggressive | Fast | Low | Rushes player |
| Defensive | Slow | High | Counter-attacks |
| Ranged | Medium | Medium | Keeps distance |
| Tank | Slow | None | Stands ground |
| Berserker | Variable | Low | Faster when hurt |
Attack patterns
| Pattern | Description |
|---|---|
| Melee | Single attack |
| Combo | 2-3 rapid attacks |
| Charged | Wind-up, stronger attack |
| Zone | 360° area attack |
| DashAttack | Rush toward target then attack |
Use skills for attacks
Examples
Basic enemy
Mage with skills
Patrol guard
Player combat
The module handles player attacks via theaction input:
Knockback system
Knockback force is driven by the equipped weapon’sknockbackForce property: