Skip to content

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.

ResourceDatabase typeHeld by
FactionDefinitionfactionNPCDefinition.faction, UniqueEntityData.faction_id
ModularBehaviorScriptbehavior_scriptNPC and class definitions, unique data
ModularCombatScriptcombat_scriptNPC and class definitions, unique data
ConversationconversationConversationInteraction.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).

MethodRule
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):

  1. Choose the schedule: the first whose activation_conditions hold and whose cooldown is over (or the fallback).
  2. Run it: an OrderedSchedule runs its tasks in sequence (looping, optionally shuffled); a PrioritySchedule re-evaluates every priority_evaluation_interval and may interrupt the current task when another has interruption_priority_threshold more priority.
  3. A BehaviorTask goes through TaskState: INACTIVE, STARTING, RUNNING, COMPLETING, COMPLETED, INTERRUPTED, FAILED. When it fails, the schedule's FailureHandling decides (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/.

StateKey facts
InactiveStateIdle; leashing: exits combat if the target is too far; goes to combat when a target is set
TargetSearchStateNPCs choose by the threat table, players and pets by proximity (nearest enemy, cached); uses the encounter's enemies so leaving combat is clean
ChasingStateLine-of-sight aware navigation; computes the attack range from the abilities; repositions when stuck
AttackingStateUpdates every 0.5 s; handles transitions and the facing of the target; the attack logic of the script uses abilities
FollowingStateFollows an entity or a position at a distance, walking or running; the formation system for pets
FleeState, DisorientedState, IncapacitatedStateEntered by crowd control effects, left when the effect ends (EffectsComponent)
PlayerCommandStateNavigates to a commanded point and returns
DeadStateDeath 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 ​

ClassWhat it is
FactionDefinitionEnhanced faction definition with reputation levels and relationships
ReputationLevelIndividual reputation level within a faction's reputation system

Behavior scripts, schedules and tasks ​

ClassWhat it is
BehaviorReactionBehaviorReaction represents an event-driven response that can switch behavior schedules.
ModularBehaviorScriptModularBehaviorScript coordinates behavior schedules and reactions for entities.
OrderedScheduleOrderedSchedule executes tasks in a defined sequence using clean signal-based communication.
PrioritySchedulePrioritySchedule executes tasks based on priority and conditions using clean signal-based communication.
TaskScheduleEnhanced TaskSchedule with comprehensive signal-based task management.
WanderScheduleWanderSchedule is a pre-configured OrderedSchedule with a single WanderTask.
ClassWhat it is
BehaviorTaskEnhanced BehaviorTask base class with comprehensive features and robust integration.
ConsumeItemTaskConsume consumable items from the entity's inventory
CreateItemTaskEmit 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
DropItemTaskThe entity puts an item on the ground where it stands: a farmer who leaves a crate, a thief who drops loot.
EquipItemTaskEquip or unequip equipment items from the entity's inventory
FollowEntityTaskFollow an entity by unique ID with proper validation and error handling.
IdleTaskModern IdleTask focused purely on positioning and waiting behavior.
InteractWithObjectTaskMake entity interact with a specific interactable object by unique ID Enhanced with proper signal-based movement handling
MoveToPointTaskComplete MoveToPointTask with all Phase 1-3 enhancements.
OpenContainerTaskOpen a specific container and optionally take/deposit items Enhanced with proper signal-based movement handling
PatrolTaskModern PatrolTask for entities that follow patrol routes.
PerformAnimationTaskSimple PerformAnimationTask using AnimationSelection resources
SayTaskThe NPC says a line or does an emote: the guard yawns while he idles, the merchant calls out his wares.
SetMetadataTaskSet, modify, or manipulate entity metadata with flexible operations
UseAbilityAtPointTaskUseAbilityAtPointTask uses a specific ability at a target point.
UseAbilityTaskUseAbilityTask uses a specific ability on the current target.
UseLadderTaskClimb a ladder (any entity can use) Enhanced with proper signal-based movement handling
UseRabbitHoleTaskUse rabbit hole for teleportation Enhanced with proper signal-based movement handling
WanderTaskWanderTask provides simple wandering behavior around a central point.

Combat scripts and actions ​

ClassWhat it is
AttackStateLogicAttackStateLogic is the base class for defining what an entity does in the ATTACKING state.
BossPhaseBossPhase represents a single phase in a boss encounter.
CombatReactionCombatReaction represents an event-driven response that can trigger in any combat state.
CompanionAttackLogicCompanionAttackLogic is what a party member does in the ATTACKING state while the player is not controlling it.
ModularCombatScriptModular combat script system that defines how an entity behaves in combat.
PhaseSystemPhaseSystem manages phase transitions for boss encounters.
PhaseTransitionDefines transition conditions for a boss phase using existing EntityCondition system
PriorityAttackLogicPriorityAttackLogic evaluates a list of actions in priority order and executes the first valid one.
SimpleAttackLogicSimpleAttackLogic automatically creates priority-based actions from the entity's active abilities.
TacticalAttackLogicTacticalAttackLogic implements dynamic decision-making for action RPG style combat.
TimelineAttackLogicTimelineAttackLogic follows a scripted sequence of actions at specific times.
ClassWhat it is
ActivateQuestCombatActionActivates a specific quest during combat
CallForHelpActionA combat action: the NPC shouts and calls the allies in range into the fight.
ClearTargetActionClears the current target
CombatActionCombatAction is the base class for all combat actions.
ComboActionComboAction executes a sequence of combat actions in order.
DelayActionDelayAction waits for a specified duration before completing.
FaceTargetActionFaceTargetAction turns the entity to face their target without moving.
KeepDistanceActionMaintains a specific distance from target by moving closer or farther as needed.
MoveToAllyPositionActionMoves to a specific ally's position based on criteria
MoveToPointActionMoveToPointAction commands the entity to move to a specific world position.
PlayStingerCombatActionPlays a stinger of the Dynamic Music that plays during a fight: the boss roars and a hit sounds over the music.
RetreatActionRetreatAction moves the entity away from their target by a specified distance.
SayCombatActionThe NPC says a line or does an emote in a fight: the boss roars at half health.
SetMusicIntensityCombatActionSets the intensity (0 to 1) of the Dynamic Music that plays during a fight: the layers of the music fade in and out.
SetMusicStateCombatActionChanges the state of the Dynamic Music that plays during a fight: a boss phase starts and the music goes to its Phase 2 state.
SpawnInteractableCombatActionSpawns an interactable during combat at a specific position
SpawnNPCCombatActionSpawns an NPC during combat at a specific position
SpawnWorldEffectCombatActionSpawns a world effect at a specific position during combat
StrafeActionStrafeAction circles around the target while maintaining facing direction.
SwitchToAllyActionSwitches target to ally based on various criteria
SwitchToEnemyActionSwitches target to enemy based on various criteria
SwitchToHighestThreatActionSwitches target to the player with highest threat (threat level) Useful for returning to primary target after using abilities on secondary targets
TriggerEventCombatActionTriggers a specific event in the event system during combat
UseAbilityActionUseAbilityAction uses a specific ability on the current target.
UseAbilityAtPointActionUseAbilityAtPointAction uses a specific ability at a target point.
WaitForConditionActionWaitForConditionAction pauses execution until a specific condition is met.

Conversations ​

ClassWhat it is
ConversationA conversation containing multiple chats and responses Responses are stored in a flat array and referenced by ID
ConversationActionBase class for all conversation actions Actions are executed when responses are chosen or chats are entered
ConversationActionEndChatEnds the current conversation This signals the conversation system to close the UI and cleanup
ConversationActionGrantRewardGrants a reward to the player Uses the Reward system for implementation
ConversationActionNewInteractionEnds the conversation and starts a different interaction The interaction is pre-initialized and cached in ConversationInstance
ConversationActionProceedToChatProceeds to a different chat in the conversation Sets the active chat and executes that chat's entry actions
ConversationActionProceedToDiceRollAction 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
ConversationActionSetResponseStateSets the active state of a response in the conversation Used to dynamically enable or disable response options
ConversationActionSetStartingChatSets which chat the conversation will start from on next interaction Useful for progressing storylines or unlocking new dialogue branches
ConversationChatA single chat in a conversation References responses by ID instead of nesting them
ConversationDiceRollDice roll / skill check node for conversation branching Supports multiple dice types and stat modifier calculations
ConversationInstanceRuntime instance of a Conversation resource Keeps the underlying resource immutable by tracking all mutable state here
ConversationResponseA single response option in a conversation Now includes chat_id to track which chat it belongs to

States (runtime) ​

ClassWhat it is
ActionStateActionState is the base class for all combat action states.
AttackingStateAttackingState represents the state when an entity is actively attacking a target.
ChasingStateChasingState with LOS-aware navigation that repositions when stuck
ClimbingStateMovementState for when entity is climbing ladders or similar traversal objects Handles path-based movement and climbing animations
DeadStateDeadState represents when an entity has been defeated.
DirectionalMovementStateMovementState for when entity is being moved by MoveDirectionalEffect Handles different movement strategies with blending animations
DisorientedStateDisorientedState represents when an entity is disoriented.
EntityStateComponentConsolidated EntityStateComponent that manages all entity state systems.
FallingStateFallingState represents the state when an entity is in mid-air, typically after walking off an edge.
FleeStateFleeState represents when an entity is fleeing from another entity.
FollowingStateFollowingState represents when an entity is following another entity or position.
IdleStateSimplified IdleState - detects stance changes and uses blending system
IdleTurningStateTurn-in-place animation while the entity turns without moving.
InactiveStateInactiveState represents when an entity is not actively engaged in combat.
IncapacitatedStateIncapacitatedState represents when an entity is completely stunned/incapacitated.
MovementDataContainer for movement information used to select appropriate animations Works with both navigation-driven and input-driven movement
MovementStateThe base of the movement states of an entity (idle, moving, falling, climbing ...).
MovementStateComponentMovementStateComponent handles the movement state system for entities.
MovingStateSimplified MovingState - passes movement data to animation player using blending system
NavigationControllerThe 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.
PlayerCommandStatePlayerCommandState represents when an entity is executing a player command.
TargetSearchStateTargetSearchState manages the search for valid targets when entity has none.