PolymorphicAI - alexneargarder/Broforce-Docs GitHub Wiki

PolymorphicAI

Table of Contents

Unity Lifecycle & Setup

Methods

protected virtual void Awake()

Unity Awake initialization. Caches references to the Unit, Mook, and PathAgent components. Calculates the block offset for grid-to-world position conversions using Map.GetUnitXOffset().


protected virtual void InitialSetup()

Performs initial AI setup including grid point calculation and special state initialization.


protected override void LateUpdate()

Unity's LateUpdate handling action queue execution and network synchronization.


protected virtual void SetDeltaTime()

Calculates and sets the delta time multiplier for AI updates. In normal mode, multiplies Time.deltaTime by 2.5 for faster AI processing. In hard mode, uses unmodified Time.deltaTime for standard speed AI.


protected virtual bool UnitCanSetup()

Determines if the unit is in a valid state to perform initial setup. By default, requires the unit to be on ground.

Returns:

  • bool: True if the unit is on ground and can be set up, false otherwise

protected virtual void Update()

Unity Update loop that drives AI behavior. Skips processing if editing, dead, or idle units are off-screen. On first frame, calls InitialSetup. Adjusts time delta for hard mode (2.5x speed). Calls Think_Networked when ready to think and not being controlled by triggers.


Fields

protected bool firstFrame = true

Flag indicating if this is the first frame of execution. Set to false after the first Update cycle to handle one-time initialization logic.


Position & Physics

Methods

public void ForceFacingDirection(int direction)

Forces the controlled unit to face a specific direction by calling the unit's ForceFaceDirection method. This immediately changes the unit's orientation.

Parameters:

  • int direction: The direction to face (1 for right, -1 for left)

public virtual Vector3 GetTargetPosition()

Gets the target position for this AI to move towards. Virtual method that derived classes must implement to provide specific targeting behavior.

Returns:

  • Vector3: The world position coordinates of the current target. Base implementation throws NotImplementedException.

protected float GetTargetX(GridPoint target)

Converts a grid column coordinate to world X position by multiplying the column by 16 and adding the block offset. Used for pathfinding and movement calculations.

Parameters:

  • GridPoint target: The grid point containing the column coordinate

Returns:

  • float: The world X position corresponding to the grid column

protected float GetTargetY(GridPoint target)

Converts a grid row coordinate to world Y position by multiplying the row by 16 and adding 12 units. This positions units slightly above the ground level of the grid cell.

Parameters:

  • GridPoint target: The grid point containing the row coordinate

Returns:

  • float: The world Y position corresponding to the grid row

Properties

public int FacingDirection { get; set; }

Gets the current facing direction of the unit this AI controls. For tank units, returns the tank's facingDirection field. For all other units, returns the sign of the transform's local scale X component (1 for right, -1 for left).

Returns:

  • int: The facing direction as an integer (1 for right, -1 for left)

protected float UnitHalfWidth { get; set; }

Gets half the width of the controlled unit, used for movement calculations and collision checks. Returns the mook's HalfWidth property if available, otherwise defaults to 4.0 units.

Returns:

  • float: Half the width of the unit in world units

Fields

public float blockOffset

X-axis offset used when converting grid positions to world coordinates. Initialized from Map.GetUnitXOffset() to ensure proper alignment with the game's grid system.


protected int lastCollumn

The column position of the AI from the previous frame. Used with lastRow to detect if the AI is stuck in the same position, triggering timeout behavior after 2 seconds.


protected int lastRow

The row position of the AI from the previous frame. Used with lastCollumn to detect if the AI is stuck in the same position, triggering timeout behavior after 2 seconds.


public int walkDirection = -1

The current horizontal movement direction of the AI. -1 for left, 1 for right. Used for movement, facing direction, and sight checks. Updated when the AI changes direction or sees enemies. Default is -1.


Character State & Effects

Methods

protected virtual void AddLaughAction()

Adds a sequence of actions to make the AI laugh at a dead player. Includes staggered timing based on laugh index, laugh animation, waiting, and looking around to ensure other threats aren't present.


public virtual GridPoint GetActionGridPoint()

Returns the target grid point of the current action, or (-1, -1) if no action is active.

Returns:

  • GridPoint: The GridPoint associated with the current action, or a GridPoint with coordinates (-1, -1) if CurrentAction is null

public virtual EnemyActionType GetActionType()

Returns the type of the current action being executed by the AI, or Wait if no action is active.

Returns:

  • EnemyActionType: The EnemyActionType of the current action, or EnemyActionType.Wait if CurrentAction is null

public virtual void HideInGrass()

Makes the AI hide in grass or foliage. Clears the action queue, adds a wait action with random duration (1-2 seconds), and sets mental state to Hiding.


protected virtual void JumpOutOfHiding()

Makes the AI jump out of hiding dramatically when alerted. Adds a short jump action followed by a 1-1.1 second wait to create a surprise emergence effect.


public virtual bool Panic(int direction, bool forgetPlayer)

Makes the AI panic and flee in a specified direction. Clears actions if changing direction, plays panic sound, sets Panicking state, and optionally forgets the player. Returns true if panic was initiated.

Parameters:

  • int direction: The direction to panic in (-1 for left, 1 for right)
  • bool forgetPlayer: Whether to forget the currently tracked player

Returns:

  • bool: True if the AI started panicking, false if already panicking

public virtual void StopBeingBlind()

Stops the AI from being blinded and returns to normal behavior. If alerted, adds BecomeIdle action; if panicking, calls StopPanicking to return to normal state.


public virtual void StopPanicking()

Stops the AI from panicking and returns to appropriate state. Calls Reassess, clears actions, and switches to Idle if no player is tracked or Alerted if still tracking a player.


Properties

protected ActionObject CurrentAction { get; set; }

Gets the action currently being executed from the action queue. Returns the first action in the queue if any exist, otherwise returns null. This represents what the AI is actively doing.

Returns:

  • ActionObject: The current ActionObject being executed, or null if the queue is empty

protected virtual bool ReadyToThink { get; set; }

Gets whether the AI is ready to make new decisions. By default, returns true when the action queue is empty, indicating no actions are pending execution. Can be overridden for custom thinking conditions.

Returns:

  • bool: True if ready to think and plan new actions, false otherwise

Fields

public float attackTime = 0.06f

Duration in seconds for the Fire action when attacking. Default value is 0.06 seconds.


public float delayBetweenFiring = 0.55f

Wait time in seconds between consecutive firing actions. Default value is 0.55 seconds. Added as a Wait action after movement during alerted state.


public float sightDelay = 0.55f

Delay in seconds before reacting to seeing an enemy. Default value is 0.55 seconds. Currently not actively used in the base implementation.


Environmental Interaction

Methods

protected virtual void CheckJumpOverStep()

Virtual method stub for checking if the AI should jump over an obstacle. The base implementation is empty, allowing derived classes to implement specific jump-over-step logic.


internal virtual void FetchObject(Transform obj)

Virtual method stub for object fetching behavior. The base implementation is empty, allowing derived classes to implement specific object fetching logic.

Parameters:

  • Transform obj: The transform of the object to fetch (unused in base implementation)

protected virtual GridPoint GetNewGridPoint()

Selects a new grid point from available patrol points, avoiding the current position when possible.

Returns:

  • GridPoint: A randomly selected GridPoint from availableGridPoints that differs from the current position, or the current position if no alternatives exist

protected bool IsBlockedForward()

Checks if the AI's forward movement is blocked by terrain using raycasting. Casts a ray from slightly behind the unit's position in the walk direction to detect ground or fragile layer obstacles within the unit's width plus a small buffer.

Returns:

  • bool: True if forward movement is blocked by terrain, false if the path is clear or if the unit is not a mook

protected bool IsGridPointAvailable(int c, int r)

Checks if a grid position is available for the AI to move to. Always returns true when panicking (ignoring patrol boundaries). Otherwise checks if the coordinates exist in the availableGridPoints list established during setup.

Parameters:

  • int c: The column coordinate to check
  • int r: The row coordinate to check

Returns:

  • bool: True if the position is available for movement, false otherwise

protected GridPoint RandomFurthestGridPoint(GridPoint currentGridPoint)

Selects a random grid point that is far from the specified position, preferring points at least 2 columns away.

Parameters:

  • GridPoint currentGridPoint: The grid point to move away from

Returns:

  • GridPoint: A GridPoint that is preferably far from currentGridPoint, or a random point if no distant points exist

protected virtual void SetupAvailableGridPoints()

Populates the available grid points list based on patrol radius and terrain walkability.


Fields

protected List<GridPoint> availableGridPoints = new List<GridPoint>()

List of grid points that are available for movement. Used when calculating patrol routes or finding valid movement destinations.


public int patrolBlocksRadius = 2

Controls how far the AI can patrol from its current position in blocks. Used in CheckPatrolBlocks to determine available grid points. Values range from 1-5, with larger values allowing the AI to patrol further. Default is 2.


public bool willClimbThroughVents

Determines whether the AI can climb through vents when calculating available patrol points. When true, the AI can move through positions that have blocks above them (vents), otherwise it avoids such positions.


AI Awareness

Methods

internal void Alert(float alertX, float alertY, bool showBubbleInstantly)

Method stub that throws NotImplementedException. Appears to be an unimplemented alert system that would have taken position coordinates and an instant bubble display flag.

Parameters:

  • float alertX: X coordinate of the alert position (unused)
  • float alertY: Y coordinate of the alert position (unused)
  • bool showBubbleInstantly: Whether to show the alert bubble immediately (unused)

public virtual void Attract(float xTarget, float yTarget)

Attracts the AI to a specific world position, typically used for distractions. Sets the attraction point, clears current actions, forgets any tracked player, adds a random wait, and switches to Attracted mental state.

Parameters:

  • float xTarget: The X world coordinate to be attracted to
  • float yTarget: The Y world coordinate to be attracted to

public virtual void Blind(float time)

Blinds the AI for a random duration between 1-1.85 seconds. Clears the action queue, forgets any seen enemy, adds a wait action, and sets mental state to Alerted.


public virtual void Blind(float time)

Blinds the AI for a specific duration. Clears the action queue, forgets any seen enemy, adds a wait action for the specified time, and sets mental state to Alerted.

Parameters:

  • float time: The duration in seconds to remain blinded

protected virtual bool CanSeeEnemyThisWay(int direction)

Checks if the AI can see an enemy in the specified direction. First attempts to detect players using HeroController visibility checks, then checks for NPC enemy units using Map visibility checks. Updates the seenEnemyNum field when an enemy is detected.

Parameters:

  • int direction: The direction to check for enemies (-1 for left, 1 for right)

Returns:

  • bool: True if an enemy is visible in the specified direction, false otherwise

protected virtual void FaceDirectionWhileAlerted(float alertX, float alertY)

Makes the AI face toward a specific position while in an alerted state. Sets walk direction toward the target and adds actions to face the point and wait briefly before continuing.

Parameters:

  • float alertX: The X world coordinate to face toward
  • float alertY: The Y world coordinate to face toward

public virtual void ForceFullyAlert()

Forces the AI to become fully alerted to the nearest player within range. Searches for players within 256 units and calls FullyAlert with the nearest player's position if found.


public virtual void ForgetPlayer()

Makes the AI forget the currently tracked player. Sets seenEnemyNum to -10 (no player) and adds a BecomeIdle action if currently in Alerted state.


public virtual void FullyAlert(float x, float y, int playerNum)

Fully alerts the AI to a player's presence at a specific position. If hiding, jumps out dramatically; otherwise shows greeting reaction, faces the player, and enters Alerted state with appropriate reaction time delay.

Parameters:

  • float x: The X world coordinate of the detected player
  • float y: The Y world coordinate of the detected player
  • int playerNum: The player number that was detected

public virtual bool GetPlayerRange(ref float xRange, ref float yRange)

Calculates the distance to the currently tracked enemy player if one exists. Sets the horizontal distance (absolute value) and vertical distance (can be negative) from the mook to the tracked player.

Parameters:

  • out float xRange: Output parameter for horizontal distance to the player
  • out float yRange: Output parameter for vertical distance to the player (positive if player is above)

Returns:

  • bool: True if a player is being tracked and range was calculated, false otherwise

public int GetSeenPlayerNum()

Gets the player number of the enemy unit currently being tracked by this AI. Returns -10 if no enemy is currently seen or tracked. Used for targeting and alert state management.

Returns:

  • int: The player number of the seen enemy, or -10 if no enemy is tracked

protected virtual void GreetPlayer()

Makes the AI unit greet the player when first spotting them. If the mook can speak, plays a greeting sound and displays an exclamation bubble. Part of the alert behavior when transitioning from unaware to alerted state.


public virtual void HearSilencedSound()

Responds to hearing a silenced weapon sound. If not already alerted and no question mark is queued, clears actions and adds a question mark reaction with wait times to simulate investigation behavior.


public virtual void HearSound(float alertX, float alertY)

Responds to hearing a loud sound at a specific position. Behavior varies by mental state: when hiding, shows a question mark; when idle, becomes suspicious and faces the sound source; when already suspicious/alerted, may turn to face if sound is behind them.

Parameters:

  • float alertX: The X world coordinate of the sound source
  • float alertY: The Y world coordinate of the sound source

public virtual void HideSpeachBubbles()

Hides both the exclamation mark and question mark speech bubbles by deactivating their game objects. Used to clear visual indicators when they are no longer needed.


public void IncrementLastAlertedTime()

Ensures the last alerted time is set to at least 1 second. Used to maintain a minimum alert duration when the AI becomes aware of threats.


protected virtual void LaughAtPlayer()

Makes the AI unit laugh at the player, typically when the player dies. Only executes if the mook can both speak and laugh. Plays a laughter sound and displays an exclamation bubble.


protected virtual void LookForEnemy()

Actively searches for enemies based on the AI's current mental state. When not hiding, checks for players and NPC enemies in the facing direction within sight range and calls FullyAlert if found. When hiding, searches for nearby players within a limited range and alerts if found. Updates seenEnemyNum when enemies are detected.


public virtual void RestartExclamationBubble_Networked()

Restarts the exclamation mark bubble animation and synchronizes it across the network. If this is the local instance, sends an RPC to other clients to restart their bubbles as well.


public virtual void RestartQuestionBubble_Networked()

Restarts the question mark bubble animation and synchronizes it across the network. If this is the local instance, sends an RPC to other clients to restart their bubbles as well.


internal virtual void ShowQuestionBubble()

Displays a question mark bubble above the AI unit and plays appropriate sound effects based on the current mental state. For Attracted state, has a 70% chance to play attracted sound, otherwise plays confused sound. For Hiding state, performs a hear sound animation. Only executes if the unit is alive and not incapacitated.


public virtual void TryForgetPlayer(int deadPayerNum)

Attempts to make the AI forget a specific player if they were tracking them. If the specified player was being tracked, adds a BecomeIdle action to the queue.

Parameters:

  • int deadPayerNum: The player number to potentially forget

public virtual void TryLaughAtDeadPlayer(int deadPayerNum)

Attempts to make the AI laugh at a dead player if it was tracking them. If the dead player was the one being tracked and the AI is visible on screen, adds laugh actions; otherwise becomes idle.

Parameters:

  • int deadPayerNum: The player number that died

public virtual void TryLooseSightOfPlayer(int hiddenPayerNum)

Handles losing sight of a tracked player. If tracking the specified player while alerted, switches to idle state with question mark and extensive look-around behavior to search for the lost target.

Parameters:

  • int hiddenPayerNum: The player number that is now hidden

Properties

public bool HasEverBeenAlerted { get; set; }

Gets whether this AI has ever entered the Alerted mental state during its lifetime. Checks if LastAlertedTime is greater than 0, indicating at least one alert has occurred.

Returns:

  • bool: True if the unit has been alerted at least once, false otherwise

public float LastAlertedTime { get; set; }

Gets the game time when this AI was last put into the Alerted mental state. Used to track how long the unit has been alerted and for AI behavior decisions. Set when transitioning to Alerted state.

Returns:

  • float: The Time.time value when last alerted, or 0 if never alerted

Fields

public ReactionBubble exclamationMark

Reference to the exclamation mark reaction bubble shown when the AI becomes alerted to enemy presence.


public int hidingLookXRange = 64

The horizontal sight range in units when the AI is in Hiding mental state. Significantly shorter than normal sight range to represent limited awareness while hiding. Default is 64 units.


private float lastAlertedTime

Tracks the time when the AI last entered the Alerted mental state. Used to determine if the AI has recently been alerted and for managing alert state transitions. A value greater than 0 indicates the AI has been alerted before.


protected int prevSeenPlayerNum = -10

Player number of the previously seen enemy. Initialized to -10 and used for tracking when the AI loses sight of a target.


public ReactionBubble questionMark

Reference to the question mark reaction bubble shown when the AI is suspicious or confused about something.


protected int seenEnemyNum = -10

Player number of the currently tracked enemy, or -10 if no enemy is being tracked. Updated when the AI spots a player through sight checks.


public int sightRangeX = 300

Horizontal sight range in pixels for detecting enemies. Default value is 300 pixels.


public int sightRangeY = 20

Vertical sight range in pixels for detecting enemies. Default value is 20 pixels, creating a narrow horizontal detection cone.


protected int suspciousThinkCount

Counter that tracks how many times the AI has performed suspicious thinking. Used in DoSuspiciousThink to determine when to change facing direction (typically after 10 think cycles). Reset when hearing sounds or changing mental states.


protected int thoughtsSincePlayerSeen

Counter that tracks how many think cycles have passed since the AI last saw an enemy. Increments each think cycle without enemy visibility. Used to determine when to change behavior (e.g., change direction after 2 cycles, become idle after 6 cycles).


Helper & Utility

Methods

private bool ActionQueueDoesntContainQuestionMark()

Checks whether the action queue contains any QuestionMark actions. Returns true if no QuestionMark actions are found, false if at least one exists. Used to prevent duplicate question mark reactions.

Returns:

  • bool: True if the queue doesn't contain any QuestionMark actions, false otherwise

public virtual bool ActionsContains(EnemyActionType enemyActionType)

Checks if the action queue contains any action of the specified type. Searches through all queued actions to find a matching type.

Parameters:

  • EnemyActionType enemyActionType: The type of action to search for in the queue

Returns:

  • bool: True if at least one action of the specified type exists in the queue; false if the queue is empty or no matching actions are found

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Adds an action to the action queue with specified queue mode behavior.

Parameters:

  • ActionObject action: The action object to add to the queue
  • QueueMode queueMode: Determines how the action is added: Clear (replaces queue), First (insert at beginning), Last (append), or AfterCurrent (insert after first action)

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Adds an action to the end of the action queue.

Parameters:

  • ActionObject action: The action object to append to the queue

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Creates and adds an action of the specified type with default duration (0.0334f).

Parameters:

  • EnemyActionType type: The type of action to create and add

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Creates and adds an action of the specified type with the specified queue mode.

Parameters:

  • EnemyActionType type: The type of action to create
  • QueueMode Qmode: The queue mode determining how the action is added to the queue

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Creates and adds an action of the specified type with custom duration.

Parameters:

  • EnemyActionType type: The type of action to create
  • float duration: The duration in seconds for the action

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Creates and adds an action with specified type, duration, and queue mode.

Parameters:

  • EnemyActionType type: The type of action to create
  • float duration: The duration in seconds for the action
  • QueueMode Qmode: The queue mode determining how the action is added

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Creates and adds an action with a target grid point location.

Parameters:

  • EnemyActionType type: The type of action to create
  • GridPoint point: The target grid point for actions like Move or FacePoint

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Creates and adds an action with target location and specified queue mode.

Parameters:

  • EnemyActionType type: The type of action to create
  • GridPoint point: The target grid point for the action
  • QueueMode Qmode: The queue mode determining how the action is added

public void AddAction(EnemyActionType type, GridPoint point, float duration)

Adds a new action to the action queue with a specific duration. This creates an ActionObject with the specified action type, target grid point, and duration, then adds it to the queue.

Parameters:

  • EnemyActionType type: The type of action to perform (Wait, Move, Fire, etc.)
  • GridPoint point: The target grid position for the action
  • float duration: The duration in seconds for the action to last

protected virtual void BecomeAlert(ActionObject currentAction)

Transitions the AI to the Alerted mental state and removes the triggering action from the queue. Called when processing a BecomeAlert action type.

Parameters:

  • ActionObject currentAction: The action object that triggered the alert transition

public virtual void CheckActionQueue()

Virtual method for checking the action queue state. The base implementation is empty, allowing derived classes to implement specific queue checking logic.


public virtual void ClearActionQueue(bool syncAfterwards)

Clears all actions from the AI's action queue. Optionally marks the queue as changed for network synchronization.

Parameters:

  • bool syncAfterwards: If true, sets hasActionQueueChanged flag to trigger network synchronization in the next update

protected void DebugShowActionQueue()

Displays debug information about the current action queue and mental state. Shows the mental state, action state, and all queued actions with their types, durations, and grid points when debug mode is enabled for this enemy.


protected void DebugShowInput(bool left, bool right, bool up, bool down, bool jump, bool climb)

Displays debug information about the current input state and pathfinding. Shows which movement directions are active and current pathfinding node information when debug mode is enabled.

Parameters:

  • bool left: Whether left movement is active
  • bool right: Whether right movement is active
  • bool up: Whether up movement is active
  • bool down: Whether down movement is active
  • bool jump: Whether jump is active
  • bool climb: Whether climb is active

public virtual void DelayedDeath(float time)

Virtual method to trigger a delayed death for the AI unit. The base implementation is empty, allowing derived classes to implement specific delayed death behavior.

Parameters:

  • float time: The delay in seconds before death occurs

public virtual void Deserialize(byte[] byteStream)

Deserializes AI state from a byte array. Base implementation does nothing.

Parameters:

  • byte[] byteStream: The byte array containing serialized AI state

public virtual void FinishResurrecting()

Called when the AI finishes a resurrection sequence. Virtual method that derived classes can override to implement post-resurrection behavior.


internal void FollowPath(NavPath path)

Assigns a navigation path to the AI's path agent and queues a FollowPath action. This clears the current action queue and adds a new action to follow the specified path to its target point.

Parameters:

  • NavPath path: The navigation path for the AI to follow

public virtual void ForceClimbing(bool leftClimb, bool rightClimb, bool topClimb)

Virtual method to force the AI into a climbing state. The base implementation is empty, allowing derived classes to implement specific climbing behavior based on the climb direction flags.

Parameters:

  • bool leftClimb: Whether the unit should climb on the left side
  • bool rightClimb: Whether the unit should climb on the right side
  • bool topClimb: Whether the unit should climb on top

public virtual SatanBossPattern GetSatanPattern()

Gets the Satan boss movement pattern. Virtual method intended for Satan boss AI implementation to override.

Returns:

  • SatanBossPattern: The current Satan boss pattern. Base implementation throws NotImplementedException.

public bool HasPathAgent()

Checks if this AI has an active pathfinding agent attached for navigation.

Returns:

  • bool: True if the pathAgent field is not null; false otherwise

protected virtual bool IsAtActionGridpoint(ActionObject currentAction)

Checks if the unit has reached the target grid position for a movement action. Compares the unit's world position to the target position, accounting for unit half-width tolerance on the X axis and exact row matching.

Parameters:

  • ActionObject currentAction: The movement action containing the target grid point

Returns:

  • bool: True if the unit has reached the target position, false otherwise

public virtual bool IsRevealed()

Checks if the AI unit is currently revealed (not hiding). A unit is considered revealed if its mental state is anything other than Hiding.

Returns:

  • bool: True if the unit is revealed (not in Hiding state), false if hiding

public virtual void Land()

Virtual method called when the AI unit lands on the ground. The base implementation is empty, allowing derived classes to implement specific landing behavior.


protected virtual void RunNormalAction(ActionObject currentAction)

Executes standard timed actions like Wait, Fire, and UseSpecial by decrementing the action's duration timer. Removes the action from the queue when the duration expires.

Parameters:

  • ActionObject currentAction: The action to process

protected virtual void RunQueue()

Processes the current action in the action queue based on its type. Handles movement, firing, special abilities, path following, state changes, and various AI behaviors. Removes completed actions and manages timeouts for stuck movement.


public virtual byte[] Serialize()

Serializes the AI state to a byte array. Base implementation returns null.

Returns:

  • byte[]: Null in the base implementation

public virtual void SetRevealed(bool revealed, float fromX, float fromY)

Sets whether the AI unit is revealed (no longer hidden). When revealing a hiding unit, changes its mental state to Idle and triggers a sound alert at the specified position.

Parameters:

  • bool revealed: Whether the unit should be revealed
  • float fromX: X coordinate of the source that revealed the unit
  • float fromY: Y coordinate of the source that revealed the unit

public virtual void StopAllActions()

Immediately stops all AI actions by clearing the action queue with synchronization enabled. This ensures the action queue change is propagated across the network.


public virtual void StopStomping()

Virtual method to stop any stomping action the AI might be performing. The base implementation is empty, allowing derived classes to implement specific stomp-stopping logic.


public void Sync(ActionObject[] queue, MentalState mentalState, float newX, float newY, int seenPlayer, ActionState state)

Synchronizes AI state from network data, updating action queue, mental state, and position.

Parameters:

  • ActionObject[] queue: Array of actions to replace the current action queue
  • MentalState mentalState: The mental state to apply
  • float newX: The X position to potentially warp to
  • float newY: The Y position to potentially warp to
  • int seenPlayer: The player number that has been seen (-10 or actual player number)
  • ActionState state: The action state to apply if position correction occurs

protected void Think_Networked()

Wrapper for Think() that only processes AI logic if the unit is alive.


Fields

public List<ActionObject> actionQueue = new List<ActionObject>()

The queue of actions this AI will perform sequentially. Each ActionObject contains an action type, optional grid point target, and duration.


private int framesSinceSync = 100

Tracks frames elapsed since last network synchronization of the action queue. Reset to 0 when syncing. Used for network optimization to avoid excessive RPC calls. Default is 100.


private bool hasActionQueueChanged

Flag indicating whether the action queue has been modified since the last network sync. Set to true when actions are added. Used to determine when to send network updates. Reset after syncing.


protected static int laughIndex

Static counter shared across all AI instances to stagger laugh timing. Increments each time a laugh action is added. Used with modulo 4 to create varied wait times (0.4s intervals) before laughing.


protected Mook mook

Reference to the Mook component if this AI controls a Mook unit. Used for Mook-specific behaviors like hiding in grass, somersaulting, and sound playback.


protected PathAgent pathAgent

The pathfinding agent component used for navigation. Handles movement calculations and obstacle avoidance for this AI.


protected RaycastHit rayCastHit

Stores raycast hit information for physics queries. Protected field available to derived classes for collision detection operations.


private int repathCount

Counter that tracks failed pathfinding attempts for the current FollowPath action. Increments when path is null. If exceeds 5, the action is cancelled. Resets to 0 when path succeeds or action completes.


protected float t

Time delta value clamped between 0 and 0.033334 seconds. Multiplied by 2.5 in Tutorial mode, used for all time-based calculations in the AI update loop.


private float timeOnSameSpot

Accumulates time in seconds when the AI remains at the same grid position. Resets when position changes. If exceeds 2 seconds, the current action is cancelled to prevent being permanently stuck.


private float timeStuckAgainstWall

Accumulates time in seconds when the AI is blocked while trying to move forward. Resets to 0 when movement succeeds. If exceeds 0.3 seconds, the current move action is cancelled.


protected Unit unit

Reference to the Unit component attached to this GameObject. Provides access to health, position, facing direction, and other unit properties.


AI Decision Making

Methods

protected virtual void DoAlertedThink()

Executes combat behavior when an enemy is seen. Fires at the target, then checks if the enemy is still visible. If the enemy is lost, increments thoughtsSincePlayerSeen and eventually returns to idle. Otherwise continues firing with movement between shots.


protected virtual void DoAttractedThink()

Executes behavior when attracted to a sound or distraction. Determines direction toward the attraction point, shows a question mark bubble (70% chance), waits briefly, then moves 2-4 spaces toward the attraction before returning to idle.


protected virtual void DoHidingThink()

Executes behavior while hiding in grass or cover. Alternates between short waits (0.25-0.3 seconds) and looking for enemies. Keeps the unit crouched and vigilant while concealed.


protected virtual void DoIdleThink()

Executes idle behavior by creating a patrol pattern. Generates 3-6 random actions alternating between waiting and moving to available grid points. If alwaysLookAround is true, adds looking actions and facing changes during the patrol.


protected virtual void DoPanicThink()

Executes panic behavior by moving 2-4 grid spaces in the current walk direction. This creates a fleeing behavior when the unit is panicked by explosions or threats.


protected virtual void DoSuspiciousThink()

Executes suspicious behavior when the AI has heard something. Adds wait and look actions to investigate. After 10 think cycles, may randomly turn around to check behind. Tracks suspicion with suspciousThinkCount.


public virtual void GetInput(ref bool left, ref bool right, ref bool up, ref bool down, ref bool jump, ref bool fire, ref bool special1, ref bool special2, ref bool special3, ref bool special4, ref bool climbButton)

Processes the current action queue and sets input flags based on the next action to execute. This is the main method that translates queued AI actions into actual control inputs.

Parameters:

  • out bool left: Set to true when the AI should move left
  • out bool right: Set to true when the AI should move right
  • out bool up: Set to true when the AI should move up
  • out bool down: Set to true when the AI should move down (also used for hiding in grass)
  • out bool jump: Set to true when the AI should jump
  • out bool fire: Set to true when the AI should fire its weapon
  • out bool special1: Set to true when the AI should use special ability 1
  • out bool special2: Set to true when the AI should use special ability 2
  • out bool special3: Set to true when the AI should use special ability 3
  • out bool special4: Set to true when the AI should use special ability 4
  • out bool climbButton: Set to true when the AI should climb

public MentalState GetThinkState()

Returns the current mental state of the AI. Used to query what behavioral state the AI is currently in.

Returns:

  • MentalState: The current MentalState (Idle, Suspicious, Alerted, Panicking, Attracted, or Hiding)

public bool IsAlerted()

Checks whether the AI is currently in the Alerted mental state. This is when the AI has confirmed sight of an enemy.

Returns:

  • bool: True if mental state is Alerted, false otherwise

public bool IsSuspicious()

Checks whether the AI is currently in the Suspicious mental state. This is when the AI has heard something but hasn't confirmed an enemy presence.

Returns:

  • bool: True if mental state is Suspicious, false otherwise

public virtual void Reassess()

Reassesses the available movement grid points for the AI unit when not in a panicking state. This method is called when the AI needs to update its understanding of where it can move, typically after environmental changes or when switching mental states.


protected virtual void RunHoverInput(ref bool left, ref bool right, ref bool up, ref bool down, ActionObject currentAction)

Handles hover input generation for AI units capable of hovering. Base implementation is empty.

Parameters:

  • out bool left: Hover left input flag
  • out bool right: Hover right input flag
  • out bool up: Hover up input flag
  • out bool down: Hover down input flag
  • ActionObject currentAction: The current hover action being processed

protected virtual void RunJumpingInput(ref bool left, ref bool right, ref bool up, ref bool down, ref bool jump, ref bool fire, ref bool special1, ref bool special2, ref bool special3, ref bool special4)

Handles input generation for the Jump action. Sets movement direction based on facing and activates jump.

Parameters:

  • out bool left: Set to true if the unit is facing left (negative scale.x)
  • out bool right: Set to true if the unit is facing right (positive scale.x)
  • out bool up: Movement up flag (not modified)
  • out bool down: Movement down flag (not modified)
  • out bool jump: Always set to true to perform the jump
  • out bool fire: Fire input flag (not modified)
  • out bool special1: Special ability 1 flag (not modified)
  • out bool special2: Special ability 2 flag (not modified)
  • out bool special3: Special ability 3 flag (not modified)
  • out bool special4: Special ability 4 flag (not modified)

protected virtual void RunMovementInput(ref bool left, ref bool right, ref bool up, ref bool down, ActionObject currentAction)

Handles movement input generation when the current action is Move type. Sets left/right flags based on target position.

Parameters:

  • out bool left: Set to true if the unit needs to move left to reach target
  • out bool right: Set to true if the unit needs to move right to reach target
  • out bool up: Movement up flag (not modified by this method)
  • out bool down: Movement down flag (not modified by this method)
  • ActionObject currentAction: The current action containing the target grid point to move to

private void RunStompingInput(ref bool left, ref bool right, ref bool up, ref bool down, ref bool jump, ref bool fire, ref bool special1, ref bool special2, ref bool special3, ref bool special4)

Handles input generation for the Stomp action. Sets movement direction and down input for stomping.

Parameters:

  • out bool left: Set to true if the unit is facing left
  • out bool right: Set to true if the unit is facing right
  • out bool up: Movement up flag (not modified)
  • out bool down: Always set to true for stomping action
  • out bool jump: Jump input flag (not modified)
  • out bool fire: Fire input flag (not modified)
  • out bool special1: Special ability 1 flag (not modified)
  • out bool special2: Special ability 2 flag (not modified)
  • out bool special3: Special ability 3 flag (not modified)
  • out bool special4: Special ability 4 flag (not modified)

public virtual void SetMentalState(MentalState newMentalState)

Sets the AI unit's mental state and performs necessary state transition logic. When transitioning to Alerted state, records the alert time. When entering Suspicious state, resets the suspicious think counter. This method can be called via RPC for network synchronization.

Parameters:

  • MentalState newMentalState: The new mental state to set (Idle, Suspicious, Alerted, Panicking, Attracted, or Hiding)

protected virtual void Think()

Main AI decision-making method that executes the appropriate thinking behavior based on the current mental state. Calls the corresponding Do[State]Think method for Idle, Suspicious, Alerted, Panicking, Attracted, or Hiding states.


Fields

public bool alwaysLookAround

When true, the AI will add look actions and face different directions during idle behavior, creating more alert-looking patrol patterns. Otherwise maintains current facing during idle movements.


protected GridPoint attractPoint

The grid point that the AI is attracted to when in Attracted mental state. Set by the Attract method and used in DoAttractedThink to move towards sounds or distractions.


public float maxIdleWaitDuration = 1f

The maximum duration in seconds for wait actions during idle behavior. Used with Random.Range to create varied wait times. Also used as duration for move actions during idle. Default is 1 second.


public MentalState mentalState

The current mental state of the AI, determining its behavior patterns. Can be Idle, Suspicious, Alerted, Panicking, Attracted, or Hiding.


public float minIdleWaitDuration = 0.3f

The minimum duration in seconds for wait actions during idle behavior. Used with Random.Range to create varied wait times. Default is 0.3 seconds.


⚠️ **GitHub.com Fallback** ⚠️