Behaviors: how they are built ​
The Behaviors chapter explains the editors. Everything here is a resource: scripts, schedules, tasks, actions and reactions have no id of their own and are saved inside the script that holds them; a script, a faction and a conversation are database resources that an NPC points to by id.
| Resource | Database type | Held by |
|---|---|---|
FactionDefinition | faction | NPCDefinition.faction, UniqueEntityData.faction_id |
ModularBehaviorScript | behavior_script | NPC and class definitions, unique data |
ModularCombatScript | combat_script | NPC and class definitions, unique data |
Conversation | conversation | ConversationInteraction.conversation_id |
Factions ​
FactionDefinition holds reputation_levels (sorted by min_reputation), faction_relationships (faction id -> a standing name, "Hostile", "Friendly" or "Neutral") and, at runtime, runtime_reputation (faction id -> a number). The built-in ids are Database.ID_ENVIRONMENTAL_FACTION (1000001) and the Player faction (1000002).
| Method | Rule |
|---|---|
is_hostile_to(id) | Never for the Environmental faction or for itself. Else the standing level (from the reputation) if it says Hostile, else the listed relationship |
is_friendly_to(id) | Always for itself. Never for Environmental. Else the standing level, else the listed relationship ("friendly" or "allied") |
is_neutral_to(id) | Always for Environmental, never for itself, else "not hostile and not friendly" |
can_target_as_enemy(id) | Always for Environmental, never for itself, else hostile or not friendly |
add_reputation, set_reputation and get_standing_level change and read the numbers. standing_changed(faction_id, old_name, new_name) is emitted when a rank changes. ReputationLevel.relationship is HOSTILE, NEUTRAL or FRIENDLY.
The behavior script ​
ModularBehaviorScript holds schedules (priority order), schedule_reactions and the fallback (FallbackBehaviorType: WANDER, MOVE_TO_SPAWN, IDLE_AT_CURRENT, FOLLOW_NEAREST_ALLY). The state component copies the script for each entity, so NPCs that share one do not share state.
Each processing step (every behavior_interval seconds, set by the level of detail):
- Choose the schedule: the first whose
activation_conditionshold and whose cooldown is over (or the fallback). - Run it: an
OrderedScheduleruns its tasks in sequence (looping, optionally shuffled); aPrioritySchedulere-evaluates everypriority_evaluation_intervaland may interrupt the current task when another hasinterruption_priority_thresholdmore priority. - A
BehaviorTaskgoes throughTaskState:INACTIVE,STARTING,RUNNING,COMPLETING,COMPLETED,INTERRUPTED,FAILED. When it fails, the schedule'sFailureHandlingdecides (SKIP_TO_NEXT,RETRY_TASK,RESTART_SCHEDULE,ABORT_SCHEDULE).
Tasks and schedules talk through signals; movement tasks set up the navigation signals before they start to move. When a path fails, PathFailureStrategy picks the recovery. Reactions (BehaviorReaction) listen to the world (player nearby, time of day, quests, events, items) and switch, pause, resume or reset the schedule, or trigger a task.
To add a task, extend BehaviorTask in a script in data_classes/entity/behavior_states/tasks/types/: the add dialog scans that folder.
The combat state machine ​
The action state is one of ModularCombatScript.ActionStateName: INACTIVE, TARGET_SEARCH, CHASING, ATTACKING, INCAPACITATED, DEAD, FOLLOWING, PLAYER_COMMAND, DISORIENTED, FLEE. The state classes are in runtime_classes/entity/components/states/action_states/.
| State | Key facts |
|---|---|
InactiveState | Idle; leashing: exits combat if the target is too far; goes to combat when a target is set |
TargetSearchState | NPCs choose by the threat table, players and pets by proximity (nearest enemy, cached); uses the encounter's enemies so leaving combat is clean |
ChasingState | Line-of-sight aware navigation; computes the attack range from the abilities; repositions when stuck |
AttackingState | Updates every 0.5 s; handles transitions and the facing of the target; the attack logic of the script uses abilities |
FollowingState | Follows an entity or a position at a distance, walking or running; the formation system for pets |
FleeState, DisorientedState, IncapacitatedState | Entered by crowd control effects, left when the effect ends (EffectsComponent) |
PlayerCommandState | Navigates to a commanded point and returns |
DeadState | Death visuals and physics; revival goes through resurrect() |
The uses_* flags of the script say which states it enters. refresh_control_state gives a party member the state of its role.
Attack logic ​
AttackStateLogic is the base: the AttackingState asks it to act. SimpleAttackLogic builds a UseAbilityAction for each active ability by itself and cycles; PriorityAttackLogic evaluates its actions by priority and runs the first whose conditions hold and that is off cooldown; TimelineAttackLogic runs timeline_actions at action_times; TacticalAttackLogic chooses by distance (melee_actions, ranged_actions, repositioning_actions); CompanionAttackLogic is the party member AI. A PhaseSystem swaps the logic per BossPhase; a PhaseTransition combines EntityConditions with AND or OR.
A CombatAction has priority, conditions, action_cooldown and interrupt_casting, and implements an execute step; ComboAction holds a sequence of actions. A CombatReaction listens to one TriggerEvent on the entity (or, for ally and enemy deaths, on the encounter) and runs its reaction_actions.
Conversations ​
A Conversation stores its conversation_chats, conversation_responses and conversation_dice_rolls in flat arrays and connects them by id, plus start_entries (dictionaries {chat_id, requirements} in priority order), the editor conversation_layout, and the quests it offers and takes in.
All runtime state is in ConversationInstance: the active chat, the response states (ConversationActionSetResponseState changes an active flag at runtime), the quest it is handing in or offering, and a starting_chat_override set by ConversationActionSetStartingChat. _evaluate_start_entries uses the override first, then the first entry whose requirements hold, then the first chat. ConversationDiceRoll.evaluate_roll(stat_value) returns the roll, the modifier, the total and the result; the instance goes to pass_chat_id or fail_chat_id. A ConversationActionNewInteraction ends the conversation and starts the interaction it holds.
Texts, voice lines and display names are arrays with one entry per language.
The classes ​
Factions ​
| Class | What it is |
|---|---|
| FactionDefinition | Enhanced faction definition with reputation levels and relationships |
| ReputationLevel | Individual reputation level within a faction's reputation system |
Behavior scripts, schedules and tasks ​
| Class | What it is |
|---|---|
| BehaviorReaction | BehaviorReaction represents an event-driven response that can switch behavior schedules. |
| ModularBehaviorScript | ModularBehaviorScript coordinates behavior schedules and reactions for entities. |
| OrderedSchedule | OrderedSchedule executes tasks in a defined sequence using clean signal-based communication. |
| PrioritySchedule | PrioritySchedule executes tasks based on priority and conditions using clean signal-based communication. |
| TaskSchedule | Enhanced TaskSchedule with comprehensive signal-based task management. |
| WanderSchedule | WanderSchedule is a pre-configured OrderedSchedule with a single WanderTask. |
| Class | What it is |
|---|---|
| BehaviorTask | Enhanced BehaviorTask base class with comprehensive features and robust integration. |
| ConsumeItemTask | Consume consumable items from the entity's inventory |
| CreateItemTask | Emit signals for item creation instead of directly creating items Allows external systems to handle item creation logic (inventory, drops, rewards, etc.) Focuses on single item creation with configurable quantity |
| DropItemTask | The entity puts an item on the ground where it stands: a farmer who leaves a crate, a thief who drops loot. |
| EquipItemTask | Equip or unequip equipment items from the entity's inventory |
| FollowEntityTask | Follow an entity by unique ID with proper validation and error handling. |
| IdleTask | Modern IdleTask focused purely on positioning and waiting behavior. |
| InteractWithObjectTask | Make entity interact with a specific interactable object by unique ID Enhanced with proper signal-based movement handling |
| MoveToPointTask | Complete MoveToPointTask with all Phase 1-3 enhancements. |
| OpenContainerTask | Open a specific container and optionally take/deposit items Enhanced with proper signal-based movement handling |
| PatrolTask | Modern PatrolTask for entities that follow patrol routes. |
| PerformAnimationTask | Simple PerformAnimationTask using AnimationSelection resources |
| SayTask | The NPC says a line or does an emote: the guard yawns while he idles, the merchant calls out his wares. |
| SetMetadataTask | Set, modify, or manipulate entity metadata with flexible operations |
| UseAbilityAtPointTask | UseAbilityAtPointTask uses a specific ability at a target point. |
| UseAbilityTask | UseAbilityTask uses a specific ability on the current target. |
| UseLadderTask | Climb a ladder (any entity can use) Enhanced with proper signal-based movement handling |
| UseRabbitHoleTask | Use rabbit hole for teleportation Enhanced with proper signal-based movement handling |
| WanderTask | WanderTask provides simple wandering behavior around a central point. |
Combat scripts and actions ​
| Class | What it is |
|---|---|
| AttackStateLogic | AttackStateLogic is the base class for defining what an entity does in the ATTACKING state. |
| BossPhase | BossPhase represents a single phase in a boss encounter. |
| CombatReaction | CombatReaction represents an event-driven response that can trigger in any combat state. |
| CompanionAttackLogic | CompanionAttackLogic is what a party member does in the ATTACKING state while the player is not controlling it. |
| ModularCombatScript | Modular combat script system that defines how an entity behaves in combat. |
| PhaseSystem | PhaseSystem manages phase transitions for boss encounters. |
| PhaseTransition | Defines transition conditions for a boss phase using existing EntityCondition system |
| PriorityAttackLogic | PriorityAttackLogic evaluates a list of actions in priority order and executes the first valid one. |
| SimpleAttackLogic | SimpleAttackLogic automatically creates priority-based actions from the entity's active abilities. |
| TacticalAttackLogic | TacticalAttackLogic implements dynamic decision-making for action RPG style combat. |
| TimelineAttackLogic | TimelineAttackLogic follows a scripted sequence of actions at specific times. |
| Class | What it is |
|---|---|
| ActivateQuestCombatAction | Activates a specific quest during combat |
| CallForHelpAction | A combat action: the NPC shouts and calls the allies in range into the fight. |
| ClearTargetAction | Clears the current target |
| CombatAction | CombatAction is the base class for all combat actions. |
| ComboAction | ComboAction executes a sequence of combat actions in order. |
| DelayAction | DelayAction waits for a specified duration before completing. |
| FaceTargetAction | FaceTargetAction turns the entity to face their target without moving. |
| KeepDistanceAction | Maintains a specific distance from target by moving closer or farther as needed. |
| MoveToAllyPositionAction | Moves to a specific ally's position based on criteria |
| MoveToPointAction | MoveToPointAction commands the entity to move to a specific world position. |
| PlayStingerCombatAction | Plays a stinger of the Dynamic Music that plays during a fight: the boss roars and a hit sounds over the music. |
| RetreatAction | RetreatAction moves the entity away from their target by a specified distance. |
| SayCombatAction | The NPC says a line or does an emote in a fight: the boss roars at half health. |
| SetMusicIntensityCombatAction | Sets the intensity (0 to 1) of the Dynamic Music that plays during a fight: the layers of the music fade in and out. |
| SetMusicStateCombatAction | Changes the state of the Dynamic Music that plays during a fight: a boss phase starts and the music goes to its Phase 2 state. |
| SpawnInteractableCombatAction | Spawns an interactable during combat at a specific position |
| SpawnNPCCombatAction | Spawns an NPC during combat at a specific position |
| SpawnWorldEffectCombatAction | Spawns a world effect at a specific position during combat |
| StrafeAction | StrafeAction circles around the target while maintaining facing direction. |
| SwitchToAllyAction | Switches target to ally based on various criteria |
| SwitchToEnemyAction | Switches target to enemy based on various criteria |
| SwitchToHighestThreatAction | Switches target to the player with highest threat (threat level) Useful for returning to primary target after using abilities on secondary targets |
| TriggerEventCombatAction | Triggers a specific event in the event system during combat |
| UseAbilityAction | UseAbilityAction uses a specific ability on the current target. |
| UseAbilityAtPointAction | UseAbilityAtPointAction uses a specific ability at a target point. |
| WaitForConditionAction | WaitForConditionAction pauses execution until a specific condition is met. |
Conversations ​
| Class | What it is |
|---|---|
| Conversation | A conversation containing multiple chats and responses Responses are stored in a flat array and referenced by ID |
| ConversationAction | Base class for all conversation actions Actions are executed when responses are chosen or chats are entered |
| ConversationActionEndChat | Ends the current conversation This signals the conversation system to close the UI and cleanup |
| ConversationActionGrantReward | Grants a reward to the player Uses the Reward system for implementation |
| ConversationActionNewInteraction | Ends the conversation and starts a different interaction The interaction is pre-initialized and cached in ConversationInstance |
| ConversationActionProceedToChat | Proceeds to a different chat in the conversation Sets the active chat and executes that chat's entry actions |
| ConversationActionProceedToDiceRoll | Action that proceeds to a dice roll / skill check Evaluates the dice roll and proceeds to success or fail chat Uses signals for clean communication with ConversationPanelUI |
| ConversationActionSetResponseState | Sets the active state of a response in the conversation Used to dynamically enable or disable response options |
| ConversationActionSetStartingChat | Sets which chat the conversation will start from on next interaction Useful for progressing storylines or unlocking new dialogue branches |
| ConversationChat | A single chat in a conversation References responses by ID instead of nesting them |
| ConversationDiceRoll | Dice roll / skill check node for conversation branching Supports multiple dice types and stat modifier calculations |
| ConversationInstance | Runtime instance of a Conversation resource Keeps the underlying resource immutable by tracking all mutable state here |
| ConversationResponse | A single response option in a conversation Now includes chat_id to track which chat it belongs to |
States (runtime) ​
| Class | What it is |
|---|---|
| ActionState | ActionState is the base class for all combat action states. |
| AttackingState | AttackingState represents the state when an entity is actively attacking a target. |
| ChasingState | ChasingState with LOS-aware navigation that repositions when stuck |
| ClimbingState | MovementState for when entity is climbing ladders or similar traversal objects Handles path-based movement and climbing animations |
| DeadState | DeadState represents when an entity has been defeated. |
| DirectionalMovementState | MovementState for when entity is being moved by MoveDirectionalEffect Handles different movement strategies with blending animations |
| DisorientedState | DisorientedState represents when an entity is disoriented. |
| EntityStateComponent | Consolidated EntityStateComponent that manages all entity state systems. |
| FallingState | FallingState represents the state when an entity is in mid-air, typically after walking off an edge. |
| FleeState | FleeState represents when an entity is fleeing from another entity. |
| FollowingState | FollowingState represents when an entity is following another entity or position. |
| IdleState | Simplified IdleState - detects stance changes and uses blending system |
| IdleTurningState | Turn-in-place animation while the entity turns without moving. |
| InactiveState | InactiveState represents when an entity is not actively engaged in combat. |
| IncapacitatedState | IncapacitatedState represents when an entity is completely stunned/incapacitated. |
| MovementData | Container for movement information used to select appropriate animations Works with both navigation-driven and input-driven movement |
| MovementState | The base of the movement states of an entity (idle, moving, falling, climbing ...). |
| MovementStateComponent | MovementStateComponent handles the movement state system for entities. |
| MovingState | Simplified MovingState - passes movement data to animation player using blending system |
| NavigationController | The path-finding and movement of an NPC: a navigation agent that moves the entity to a position, follows a target, or takes direct movement input. |
| PlayerCommandState | PlayerCommandState represents when an entity is executing a player command. |
| TargetSearchState | TargetSearchState manages the search for valid targets when entity has none. |