Okay, this is a great problem! You're aiming for a flexible, state-driven character controller with modular actions, handling tricky animation/hitbox synchronization, and wanting a clean, reusable, yet type-safe structure. Let's break this down and build a conceptual framework.
Core Concepts:
- State Machine: Essential for managing different behaviors (Ground, Air, Dashing, Attacking, etc.).
- Scriptable Objects (SOs): Perfect for defining modular actions, states, and their configurations (animations, timings, parameters) data-driven way. This allows drag-and-drop and easy modification without code changes.
- Context Object: A central piece of data passed around that represents the character being controlled, providing access to its components (Animator, Rigidbody, etc.) and potentially character-specific data.
- Action Abstraction: Define interfaces and base classes for actions that can be implemented by specific behaviors.
- Manual Animation Timing: Avoid relying solely on Animation Events. Use timers within your actions synchronized with the Animator's playback state.
Framework Structure:
Let's define the key C# scripts and ScriptableObjects:
1. The Character Controller (MonoBehaviour)
This is the main brain attached to your character GameObject.
using UnityEngine;
using UnityEngine.InputSystem;
// Interface for context passed to states and actions
public interface ICharacterContext
{
Animator Animator { get; }
Rigidbody2D Rigidbody { get; }
Transform Transform { get; }
// Add other essential components or data interfaces here
bool IsGrounded { get; } // Example property managed by a GroundCheck component
// Method to trigger state changes
void ChangeState(CharacterStateData newStateData);
// Method to try and activate an action
bool TryActivateAction(InputAction action, InputData inputData);
// Methods to interact with gameplay systems like hitboxes
HitboxController GetHitboxController();
void ApplyVelocity(Vector2 velocity, bool overrideCurrent = false);
void AddForce(Vector2 force);
// ... etc
}
public class CharacterController : MonoBehaviour, ICharacterContext
{
[Header("Core Components")]
[SerializeField] private Animator animator;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private GroundCheck groundCheck; // Assume this component sets IsGrounded
[SerializeField] private HitboxController hitboxController; // Assume this handles hitboxes
[Header("State Configuration")]
[SerializeField] private CharacterStateData initialStateData; // Assign your GroundState SO here
// Input Handling
private PlayerInput playerInput;
private InputActionAsset inputActions; // Assign your Input Actions asset
private Dictionary<string, InputAction> activeInputActions = new Dictionary<string, InputAction>();
// State Management
private IState currentStateInstance;
public CharacterStateData CurrentStateData { get; private set; }
// Action Instances (SO instances are singletons, need runtime data)
private Dictionary<CharacterActionData, RuntimeAction> actionInstances = new Dictionary<CharacterActionData, RuntimeAction>();
void Awake()
{
if (animator == null) animator = GetComponentInChildren<Animator>();
if (rb == null) rb = GetComponent<Rigidbody2D>();
if (groundCheck == null) groundCheck = GetComponent<GroundCheck>();
if (hitboxController == null) hitboxController = GetComponent<HitboxController>();
// Setup Input System
playerInput = GetComponent<PlayerInput>();
if (playerInput != null && inputActions != null)
{
playerInput.actions = inputActions;
foreach (var actionMap in inputActions.actionMaps)
{
foreach (var action in actionMap.actions)
{
if (action.bindings.Count > 0) // Only care about actions with bindings
{
// Ensure the action is enabled and subscribe
var boundAction = playerInput.actions[action.name];
boundAction.Enable();
boundAction.performed += OnActionPerformed;
activeInputActions.Add(action.name, boundAction);
}
}
}
}
else { Debug.LogError("Input Actions asset or PlayerInput not configured!"); }
// Initialize State
ChangeState(initialStateData);
}
// --- ICharacterContext Implementation ---
public Animator Animator => animator;
public Rigidbody2D Rigidbody => rb;
public Transform Transform => transform;
public bool IsGrounded => groundCheck.IsGrounded; // Delegate to GroundCheck
public HitboxController GetHitboxController() => hitboxController;
public void ChangeState(CharacterStateData newStateData)
{
if (newStateData == null) return;
CurrentStateData = newStateData;
currentStateInstance?.Exit(this); // Exit previous state
// Create or get runtime instance of the state's logic handler
currentStateInstance = CurrentStateData.GetStateInstance(this);
currentStateInstance.Enter(this);
}
public bool TryActivateAction(InputAction action, InputData inputData)
{
if (CurrentStateData == null || !CurrentStateData.ActionMappings.TryGetValue(action.name, out CharacterActionData actionData))
{
// Action not mapped in current state
return false;
}
// Get or create the runtime instance for this action SO
RuntimeAction runtimeAction = GetOrCreateActionInstance(actionData);
// Pass context and input data to the action's activation logic
return runtimeAction.TryActivate(this, inputData);
}
private RuntimeAction GetOrCreateActionInstance(CharacterActionData actionData)
{
if (!actionInstances.TryGetValue(actionData, out RuntimeAction instance))
{
instance = actionData.CreateRuntimeInstance();
actionInstances.Add(actionData, instance);
}
return instance;
}
// --- End ICharacterContext ---
void OnActionTriggered(InputAction.CallbackContext context)
{
// Check if the action is defined in the current state's mappings
if (CurrentStateData != null && CurrentStateData.ActionMappings.TryGetValue(context.action.name, out CharacterActionData actionData))
{
// Prepare input data (value, isPressed, etc.)
InputData inputData = new InputData {
value = context.ReadValue<float>(), // For triggers, sticks
isPressed = context.phase == InputActionPhase.Performed,
isReleased = context.phase == InputActionPhase.Canceled
};
// Attempt activation
TryActivateAction(context.action, inputData);
}
}
// Example: Simplified Input Handling (Hook up PlayerInput Component's Events)
// You might need more sophisticated handling for different input types (button press vs. stick tilt)
void OnActionPerformed(InputAction action)
{
// This event fires once when the action is performed.
// We might need to read stick values or check button states here.
// Let's refine TryActivateAction to handle this better.
// We can create a wrapper or use action callbacks directly.
// For simplicity, let's assume CharacterController calls TryActivateAction when input is detected.
// A better way is to use the PlayerInput events directly.
// *** Revised Input Approach using PlayerInput Events ***
// PlayerInput component has events like `actions.FindAction("Attack").performed += ctx => HandleAttack(ctx);`
// In Awake:
// foreach (var map in playerInput.actions.actionMaps) {
// foreach (var action in map.actions) {
// action.performed += ctx => OnActionTriggered(ctx); // Subscribe all actions
// }
// }
}
void Update()
{
// Let the current state handle per-frame updates
currentStateInstance?.Tick(Time.deltaTime);
}
void FixedUpdate()
{
// Let the current state handle physics updates
currentStateInstance?.FixedTick(Time.fixedDeltaTime);
}
// --- Movement/Physics Helpers ---
public void ApplyVelocity(Vector2 velocity, bool overrideCurrent = false)
{
if (overrideCurrent) rb.velocity = velocity;
else rb.velocity = velocity; // Or blend based on override flag logic
}
public void AddForce(Vector2 force) { rb.AddForce(force, ForceMode2D.Impulse); }
// --- Cleanup ---
void OnDestroy()
{
// Unsubscribe from input actions to prevent memory leaks
if (playerInput != null)
{
foreach (var action in activeInputActions.Values)
{
action.performed -= OnActionPerformed;
}
}
// Explicitly clean up actions if needed
foreach(var instance in actionInstances.Values) {
instance.Cleanup();
}
}
}
// Data structure for input details
public struct InputData
{
public float value; // e.g., stick tilt magnitude
public bool isPressed;
public bool isReleased;
// Add vector if needed, e.g., Vector2 stickDirection
}
// GroundCheck Component (Example)
public class GroundCheck : MonoBehaviour
{
public bool IsGrounded { get; private set; }
// ... implementation using Raycast, CircleCast, or Collision events ...
void OnTriggerStay2D(Collider2D other) { IsGrounded = true; } // Simplified
void OnTriggerExit2D(Collider2D other) { IsGrounded = false; } // Simplified
}
// HitboxController Component (Example)
public class HitboxController : MonoBehaviour
{
private Collider2D currentHitboxCollider;
private float hitboxActiveStartTime;
private float hitboxActiveEndTime;
private bool isHitboxActive = false;
public void ActivateHitbox(Collider2D hitboxCollider, float activeDuration) {
// Assumes the collider is already part of the GameObject or instantiated
currentHitboxCollider = hitboxCollider;
if(currentHitboxCollider != null) {
currentHitboxCollider.enabled = true;
isHitboxActive = true;
hitboxActiveStartTime = Time.time; // For potential timing logic
hitboxActiveEndTime = Time.time + activeDuration;
}
}
public void ActivateHitbox(Collider2D hitboxCollider, float startTime, float endTime) {
// For frame-based activation managed by the action
currentHitboxCollider = hitboxCollider;
if(currentHitboxCollider != null) {
currentHitboxCollider.enabled = true;
isHitboxActive = true;
hitboxActiveStartTime = startTime;
hitboxActiveEndTime = endTime;
}
}
public void DeactivateHitbox() {
if(currentHitboxCollider != null) {
currentHitboxCollider.enabled = false;
isHitboxActive = false;
currentHitboxCollider = null;
}
}
// Called potentially by Update or FixedUpdate if the action needs continuous checks
public void UpdateHitboxState() {
if(isHitboxActive && Time.time >= hitboxActiveEndTime) {
DeactivateHitbox();
}
}
// Handle Collision Logic (OnTriggerEnter2D etc.) to apply damage etc.
void OnTriggerEnter2D(Collider2D other) {
if(isHitboxActive && currentHitboxCollider != null /* && Check if 'other' is a valid target */ ) {
Debug.Log($"Hitbox hit: {other.gameObject.name}");
// Apply damage, status effects, etc. to 'other'
// Potentially disable hitbox after first hit depending on design
// DeactivateHitbox();
}
}
}
2. States (ScriptableObjects)
Define the data and configuration for each state.
using UnityEngine;
using System.Collections.Generic;
// Base class for state data
public abstract class CharacterStateData : ScriptableObject
{
// Maps Input Action names to the specific Action Data SOs for this state
public Dictionary<string, CharacterActionData> ActionMappings = new Dictionary<string, CharacterActionData>();
// Abstract method to get the runtime state instance
public abstract IState GetStateInstance(ICharacterContext context);
}
// Concrete State Data for Grounded State
[CreateAssetMenu(menuName = "Character/States/Ground State")]
public class GroundStateData : CharacterStateData
{
[Header("Ground Specific")]
public float walkSpeed = 5f;
public float runSpeed = 8f;
public float jumpForce = 10f;
// Map actions via Inspector or code during setup
// Example: Add actions like this (or better, via a setup step):
// public CharacterActionData groundAttackAction;
// public CharacterActionData dashAction;
public override IState GetStateInstance(ICharacterContext context)
{
// Return a runtime instance of the Ground State logic
return new GroundState(this, context);
}
}
// Concrete State Data for Air State
[CreateAssetMenu(menuName = "Character/States/Air State")]
public class AirStateData : CharacterStateData
{
[Header("Air Specific")]
public float airMoveSpeed = 4f;
public float gravityScale = 2f;
public float fallTerminalVelocity = -15f;
// Map actions specifically for air state
// public CharacterActionData airDashAction;
// public CharacterActionData airAttackAction;
public override IState GetStateInstance(ICharacterContext context)
{
return new AirState(this, context);
}
}
// Interface for runtime state logic handlers
public interface IState
{
void Enter(ICharacterContext context);
void Tick(float deltaTime);
void FixedTick(float fixedDeltaTime);
void Exit(ICharacterContext context);
}
// --- Runtime State Implementations ---
public class GroundState : IState
{
private GroundStateData stateData;
private ICharacterContext context;
private float currentHorizontalInput;
public GroundState(GroundStateData data, ICharacterContext ctx)
{
stateData = data;
context = ctx;
}
public void Enter(ICharacterContext context)
{
context.Animator.SetBool("IsGrounded", true); // Example animation parameter
context.Rigidbody.gravityScale = 0; // Or base gravity
// Reset any air-specific states
}
public void Tick(float deltaTime)
{
// Read horizontal input for movement direction
currentHorizontalInput = Input.GetAxisRaw("Horizontal"); // Use Input System later
// Handle non-physics based actions (e.g., simple button presses)
// Action activation is now handled by CharacterController reacting to input events
// Check for Jump Hold for Vault (example)
// Requires state to track jump input state
}
public void FixedTick(float fixedDeltaTime)
{
// Handle physics-based movement
float targetSpeed = stateData.walkSpeed;
// Add logic for running based on another input if needed
// if (Input.GetKey(KeyCode.LeftShift)) targetSpeed = stateData.runSpeed;
Vector2 velocity = context.Rigidbody.velocity;
velocity.x = currentHorizontalInput * targetSpeed;
context.ApplyVelocity(velocity, true); // Override velocity for direct control
context.Animator.SetFloat("Speed", Mathf.Abs(velocity.x)); // Animation
}
public void Exit(ICharacterContext context)
{
context.Animator.SetBool("IsGrounded", false);
// context.Rigidbody.gravityScale = stateData.gravityScale; // Or some default
}
}
public class AirState : IState
{
private AirStateData stateData;
private ICharacterContext context;
private float currentHorizontalInput;
private float currentVerticalInput; // For air control direction
public AirState(AirStateData data, ICharacterContext ctx)
{
stateData = data;
context = ctx;
}
public void Enter(ICharacterContext context)
{
context.Animator.SetBool("IsGrounded", false);
context.Rigidbody.gravityScale = stateData.gravityScale;
}
public void Tick(float deltaTime)
{
currentHorizontalInput = Input.GetAxisRaw("Horizontal"); // Use Input System later
currentVerticalInput = Input.GetAxisRaw("Vertical"); // Use Input System later
// Apply gravity manually if needed or rely on Rigidbody's scale
Vector2 velocity = context.Rigidbody.velocity;
if (velocity.y > stateData.fallTerminalVelocity) // Apply terminal velocity
{
velocity.y = Mathf.Max(velocity.y, stateData.fallTerminalVelocity);
}
// Apply air friction/drag manually if desired
context.Rigidbody.velocity = velocity;
// Action activation handled by CharacterController reacting to input events
}
public void FixedTick(float fixedDeltaTime)
{
// Limited air control
Vector2 velocity = context.Rigidbody.velocity;
// Simple dampening or direct velocity setting for air control
velocity.x = Mathf.MoveTowards(velocity.x, currentHorizontalInput * stateData.airMoveSpeed, stateData.airMoveSpeed * fixedDeltaTime); // Example control
context.Rigidbody.velocity = velocity;
}
public void Exit(ICharacterContext context)
{
context.Rigidbody.gravityScale = 0; // Reset gravity scale
}
}
3. Actions (ScriptableObjects)
Define the data and configuration for reusable actions.
using UnityEngine;
using System.Collections.Generic;
// Structure to hold animation and hitbox timing data
[System.Serializable]
public class AnimationTimingData
{
public string animationClipName; // Name of the animation clip to play
// Timing info: Frames or seconds
public int hitboxActiveStartFrame = -1;
public int hitboxActiveEndFrame = -1;
public float hitboxActiveStartTime = -1f; // Alternative: use seconds
public float hitboxActiveEndTime = -1f;
public float actionDuration = 0.5f; // How long the action generally lasts
// Add damage values, hitbox prefabs/references etc. here
public GameObject hitboxPrefab; // Or reference to a Collider2D component to enable
}
// Base class for all Character Actions
public abstract class CharacterActionData : ScriptableObject
{
public string ActionName = "Unnamed Action";
public AnimationTimingData animationTiming;
// Method to create the runtime instance of the action
public abstract RuntimeAction CreateRuntimeInstance();
// The core logic will be in the RuntimeAction class
}
// Interface for runtime action instances
public interface ICharacterAction
{
// Check prerequisites and initiate the action
bool TryActivate(ICharacterContext context, InputData inputData);
// Update logic (called by CharacterController.Update)
void Tick(float deltaTime);
// Physics logic (called by CharacterController.FixedUpdate)
void FixedTick(float fixedDeltaTime);
// Cleanup when action ends or is interrupted
void Cleanup();
}
// Base class for Runtime Action Instances (holds state)
public abstract class RuntimeAction
{
protected CharacterActionData actionData;
protected ICharacterContext context;
protected InputData currentInput;
protected bool isActive = false;
protected float timer = 0f;
protected int currentFrame = 0; // If tracking frames manually
// Store animation state info if needed
protected string lastPlayedAnimation = null;
public RuntimeAction(CharacterActionData data)
{
actionData = data;
}
public virtual bool TryActivate(ICharacterContext context, InputData inputData)
{
// Basic checks: is already active? Can activate?
if (isActive) return false;
if (!CanActivate(context, inputData)) return false;
this.context = context;
this.currentInput = inputData;
this.isActive = true;
this.timer = 0f;
this.currentFrame = 0; // Reset frame counter
// --- Animation & Hitbox Setup ---
// 1. Play the animation specified in actionData.animationTiming
if (!string.IsNullOrEmpty(actionData.animationTiming.animationClipName))
{
// Consider Animator parameters: SetTrigger, SetBool, SetFloat, SetInteger
// Using a trigger might be simplest if actions are distinct, or use state names
context.Animator.Play(actionData.animationTiming.animationClipName);
lastPlayedAnimation = actionData.animationTiming.animationClipName; // Store for potential checks
}
// 2. Prepare Hitbox (don't activate yet, wait for timing)
// The HitboxController might need enabling/disabling. Let's assume it manages internal state.
// We need a reference to the specific hitbox collider defined for this action.
// This might involve prefab instantiation or enabling child colliders.
// For now, let's assume HitboxController can be told which hitbox to manage.
// We'll pass timing info to the action's Tick method.
// Call specific Enter logic
Enter(context, inputData);
return true;
}
// Specific activation prerequisites check
protected abstract bool CanActivate(ICharacterContext context, InputData inputData);
// Specific enter logic (e.g., applying initial velocity for dash)
protected virtual void Enter(ICharacterContext context, InputData inputData) { }
public virtual void Tick(float deltaTime)
{
if (!isActive) return;
timer += deltaTime;
// If using frame counting:
// currentFrame = context.Animator.GetCurrentAnimatorStateInfo(0).normalizedTime calculation? Risky.
// Better: Estimate based on assumed frame rate or calculate based on clip length.
// Let's use timer for now, assuming ClipLength is known or estimated.
float animationNormalizedTime = timer / actionData.animationTiming.actionDuration; // Approximate
// Check Hitbox Timing (using seconds for simplicity here)
bool shouldActivateHitbox = timer >= actionData.animationTiming.hitboxActiveStartTime &&
timer < actionData.animationTiming.hitboxActiveEndTime;
if (shouldActivateHitbox) {
// Activate hitbox logic
if(actionData.animationTiming.hitboxPrefab != null) {
// Logic to instantiate or enable the correct hitbox collider
// context.GetHitboxController().ActivateHitbox(timingData.startTime, timingData.endTime);
// Let's refine: maybe pass the specific collider reference?
// Option: Define hitbox collider ref in SO, find it on context, enable it.
// context.GetHitboxController().ActivateHitbox(specificHitboxColliderRef, timer, timer + deltaTime); // Example
}
}
// Check if action is finished
if (timer >= actionData.animationTiming.actionDuration)
{
FinishAction();
}
}
public virtual void FixedTick(float fixedDeltaTime)
{
if (!isActive) return;
// Handle physics updates (e.g., dashing velocity)
HandlePhysics(fixedDeltaTime);
}
protected virtual void HandlePhysics(float fixedDeltaTime) {} // To be overridden by subclasses like Dash
// Call this when the action is complete or interrupted
protected virtual void FinishAction()
{
isActive = false;
timer = 0f;
currentFrame = 0;
context.GetHitboxController().DeactivateHitbox(); // Ensure hitbox is off
Cleanup(); // Specific cleanup
// Transition back to appropriate state (e.g., Ground or Air)
// This logic might belong in the CharacterController or the state itself
// Example: Tell controller to switch state based on context properties
// context.ChangeState(context.IsGrounded ? GroundStateData : AirStateData); // Need references to these SOs! Pass them in context.
}
public virtual void Cleanup()
{
// Reset any temporary states or flags
isActive = false;
timer = 0f;
currentFrame = 0;
lastPlayedAnimation = null;
}
}
// --- Concrete Action Implementations ---
// Example: Dash Action Data
[CreateAssetMenu(menuName = "Character/Actions/Dash Action")]
public class DashActionData : CharacterActionData
{
public float dashSpeed = 20f;
public float dashDuration = 0.25f;
public bool canAirDash = true;
// public GroundStateData defaultReturnState; // Need references to SOs
// public AirStateData defaultAirReturnState;
public override RuntimeAction CreateRuntimeInstance()
{
return new DashRuntimeAction(this);
}
}
public class DashRuntimeAction : RuntimeAction
{
private DashActionData DashData => (DashActionData)actionData; // Cast for convenience
private Vector2 dashDirection;
public DashRuntimeAction(DashActionData data) : base(data)
{
// Initialize data specific to this instance if needed
actionData.animationTiming.actionDuration = dashData.dashDuration; // Set duration from data
}
protected override bool CanActivate(ICharacterContext context, InputData inputData)
{
// Check prerequisites
if (!context.IsGrounded && !DashData.canAirDash) return false;
// Could add checks like "Is already dashing?" or resource checks
return true;
}
protected override void Enter(ICharacterContext context, InputData inputData)
{
// Determine dash direction based on input or facing direction
// Let's assume horizontal input determines direction
float horizontalInput = Input.GetAxisRaw("Horizontal"); // Better: Get from InputData or context
if (Mathf.Abs(horizontalInput) < 0.1f) {
horizontalInput = context.Transform.localScale.x > 0 ? 1f : -1f; // Dash forward if no input
}
dashDirection = new Vector2(horizontalInput, 0).normalized;
// Apply initial velocity
context.ApplyVelocity(dashDirection * DashData.dashSpeed, true);
// Maybe disable gravity during dash?
// context.Rigidbody.gravityScale = 0;
}
protected override void HandlePhysics(float fixedDeltaTime)
{
// Keep applying velocity or let inertia handle it based on design
// For a short burst, applying initial velocity might be enough.
// For longer dashes, you might need continuous force or velocity clamping.
// context.ApplyVelocity(dashDirection * DashData.dashSpeed, true);
}
protected override void FinishAction()
{
// Reset gravity if it was changed
// context.Rigidbody.gravityScale = context.IsGrounded ? 0 : stateData.gravityScale; // Need state data ref
// If dash duration is short, timer check is sufficient.
// If dash has physics, ensure velocity is handled.
base.FinishAction(); // Calls Cleanup, handles state transition attempt
}
// Override Cleanup if specific reset needed for dash
public override void Cleanup()
{
base.Cleanup();
// Any dash-specific cleanup
dashDirection = Vector2.zero;
}
}
// Example: Attack Action Data
[CreateAssetMenu(menuName = "Character/Actions/Attack Action")]
public class AttackActionData : CharacterActionData
{
public CombatType combatType = CombatType.Light;
public HitboxDefinition[] hitboxes; // Array of hitbox data
public override RuntimeAction CreateRuntimeInstance()
{
return new AttackRuntimeAction(this);
}
}
public enum CombatType { Light, Heavy, Special }
[System.Serializable]
public class HitboxDefinition {
public string hitboxName; // Identifier for the specific hitbox collider (e.g., "PunchHitbox")
public int frameStart;
public int frameEnd;
public float damage;
// public Vector2 offset; // Offset relative to character transform
// public Vector2 size; // Size of the hitbox
}
public class AttackRuntimeAction : RuntimeAction
{
private AttackActionData AttackData => (AttackActionData)actionData;
private Collider2D activeHitboxCollider; // Reference to the currently enabled hitbox
public AttackRuntimeAction(AttackActionData data) : base(data)
{
// Set duration based on animation if not set in timing data, or calculate based on frames
if (data.animationTiming.actionDuration <= 0 && data.hitboxes.Length > 0) {
// Try to estimate duration based on frames - requires knowing animation FPS
// actionData.animationTiming.actionDuration = (float)data.hitboxes.Max(h => h.frameEnd) / assumedFPS;
}
}
protected override bool CanActivate(ICharacterContext context, InputData inputData)
{
// Can attack if grounded or in air (unless specific restrictions)
return true; // Add more checks if needed
}
protected override void Enter(ICharacterContext context, InputData inputData)
{
base.Enter(context, inputData); // Plays animation
// Find and prepare the hitbox collider based on data.
// This requires the HitboxController or CharacterController to have a way
// to map hitbox names/definitions to actual Collider2D components.
// Example: Find the collider named "PunchHitbox" associated with this action.
// activeHitboxCollider = context.FindHitboxCollider(AttackData.hitboxes[0].hitboxName); // Assuming method exists
}
// Override Tick for Frame-Based Hitbox Activation
public override void Tick(float deltaTime)
{
if (!isActive) return;
// Frame Counting Logic (Requires Animator Frame Info or Manual Tracking)
// This is the tricky part. Let's simulate frame tracking.
// Assume CharacterController can provide current frame or normalized time precisely.
// --- Option 1: Timer Approximation (as before) ---
timer += deltaTime;
float normalizedTime = timer / actionData.animationTiming.actionDuration; // Approximate
// --- Option 2: Get precise frame data (if possible) ---
// This is what you want to avoid animation events for.
// You might need custom Animator state machine behaviours or direct sampling.
// Let's stick to the timer and expose frame data in AnimationTimingData for clarity.
// Example using defined frames (assuming character animation runs at a consistent FPS, e.g., 60fps)
int currentAnimFrame = Mathf.FloorToInt(timer * 60.0f); // Assuming 60 FPS animation
foreach (var hitboxDef in AttackData.hitboxes)
{
bool hitboxShouldBeActive = currentAnimFrame >= hitboxDef.frameStart && currentAnimFrame < hitboxDef.frameEnd;
if (hitboxShouldBeActive)
{
// Check if hitbox needs activation *now*
// Need a way to link hitboxDef to the actual collider and the HitboxController
// Let's assume HitboxController has a method:
// ActivateHitbox(string hitboxName, float damage, float startTime, float endTime)
// This is getting complex. Simpler: Activate specific collider.
// Find the collider reference using hitboxDef.hitboxName
// Collider2D specificCollider = context.GetHitboxColliderComponent(hitboxDef.hitboxName);
// if (specificCollider != null) {
// context.GetHitboxController().ActivateHitbox(specificCollider, hitboxDef.damage); // Needs modification in HitboxController
// }
}
else
{
// Ensure hitbox is deactivated if it was active but is no longer in range for this definition
// context.GetHitboxController().DeactivateHitbox(hitboxDef.hitboxName);
}
}
// --- Simplified Hitbox Handling using the base RuntimeAction timing ---
// If using base timing (start/end time):
bool hitboxActive = timer >= actionData.animationTiming.hitboxActiveStartTime && timer < actionData.animationTiming.hitboxActiveEndTime;
if (hitboxActive) {
// Activate the pre-assigned hitbox collider reference
// context.GetHitboxController().ActivateHitbox(activeHitboxCollider, /* damage */);
}
// Check action end condition
if (timer >= actionData.animationTiming.actionDuration)
{
FinishAction();
}
}
// Override FixedTick if attack has physics interaction
protected override void HandlePhysics(float fixedDeltaTime)
{
// E.g., If attack pushes the enemy back
}
protected override void FinishAction()
{
// Ensure hitbox is definitely deactivated before finishing
context.GetHitboxController().DeactivateHitbox(); // Ensure it's off
activeHitboxCollider = null;
base.FinishAction();
}
}
// --- Input Data Handling ---
// Need to properly capture input values (like stick tilt) when actions are performed.
// Modify OnActionTriggered in CharacterController to pass relevant data.
4. Input System Integration
- Create an Input Actions asset (
.inputactions).
- Define actions like "Move" (Stick, Vector2), "Attack" (Button), "Dash" (Button), "Jump" (Button), "Special" (Button), "UpTilt" (Button/Composite), "DownTilt" (Button/Composite).
- Use composites for directional attacks (e.g., Up + Attack).
- Attach the
PlayerInput component to your character GameObject. Assign the Input Actions asset.
- Set
Behavior to "Invoke Unity Events" or "Send Messages".
- In
CharacterController.Awake():
- Get the
PlayerInput component.
- Subscribe to
action.performed events for each relevant action (as shown partially in the revised Awake). This is generally more robust than using Unity Events or Send Messages for complex logic.
- Store references to the
InputAction objects.
5. State & Action Linking (Configuration)
This is key for the drag-and-drop modularity.
- Create ScriptableObjects: Create SO assets for each state (
GroundStateData, AirStateData) and each action (DashActionData, AttackActionData).
- Configure State SOs:
- In the Inspector for
GroundStateData, create a Dictionary<string, CharacterActionData> (or use a list of pairs if you don't have dictionary serialization).
- Map Input Action names (e.g.,
"Attack", "Dash") to the corresponding Action SO assets (MyGroundAttackData, MyDashData).
- Do the same for
AirStateData, potentially linking "Dash" to AirDashData.
- Configure Action SOs:
- Set the
animationClipName in the AnimationTimingData.
- Define
hitboxActiveStartTime/EndTime or hitboxActiveStartFrame/EndFrame. Crucially, you need a way to know the animation's FPS or total duration. This might be stored in the SO or retrieved from the Animator clip asset at runtime.
- Assign specific parameters like
dashSpeed, damage, etc.
6. Handling the Animation/Hitbox Sync Problem
- No Animation Events: We are not using Animation Events to trigger hitbox logic.
- Action Timer: The
RuntimeAction (like DashRuntimeAction, AttackRuntimeAction) maintains its own timer.
- Timing Data: The
AnimationTimingData within the CharacterActionData SO defines when during the action's duration the hitboxes should be active. This can be defined in seconds (hitboxActiveStartTime, hitboxActiveEndTime) or frames (hitboxActiveStartFrame, hitboxActiveEndFrame).
- Manual Calculation: Inside the
RuntimeAction.Tick() method:
- Increment the timer.
- Calculate the animation's approximate normalized time (
timer / actionDuration).
- Compare the timer (or calculated frame number) against the
AnimationTimingData.
- If the timing matches, call the
HitboxController to activate/deactivate the appropriate hitbox. The HitboxController needs a way to identify which hitbox to activate (e.g., by name, or by passing a reference to the collider).
- Hitbox Controller: The
HitboxController manages the actual Collider2D components. It might have methods like ActivateHitbox(string hitboxName, float damage) or ActivateHitbox(Collider2D collider, float damage). The RuntimeAction needs to tell it which one and when.
7. Type Safety and Reusability
ICharacterContext: This interface provides a contract for accessing components. The CharacterController implements it.
- Action Activation:
CharacterController.TryActivateAction takes the InputAction and InputData. It finds the correct CharacterActionData SO based on the current state and input action name.
- Runtime Instances: We use
RuntimeAction classes derived from RuntimeAction to hold the state (timer, active status) for each currently executing action. The CharacterActionData SO acts as the blueprint/template.
- Specific References: When an action needs player-specific data (like a
Player component), the RuntimeAction receives the ICharacterContext. Inside its methods (CanActivate, Enter, Tick), it can query the context:
// Inside a RuntimeAction method:
if (context.TryGetComponent<Player>(out Player playerComponent))
{
// Use playerComponent.specialResource, etc.
}
else if (context.TryGetComponent<EnemyAI>(out EnemyAI enemyComponent))
{
// Use enemyComponent.aggroRadius, etc.
}
This avoids generics in the base framework but allows specific type access where needed. You simply need to ensure your CharacterController has the correct components attached for the specific character type. The CharacterStateData and CharacterActionData SOs are shared across different character types, but you'd create different instances of these SOs, configured appropriately for each character.
Summary of Workflow:
- Setup: Create State SOs (
GroundStateData, AirStateData) and Action SOs (DashActionData, AttackActionData, etc.). Configure the mappings in the State SOs (Input Action Name -> Action SO). Assign the initial State SO to the CharacterController.
- Input: Player presses a button (e.g., Attack). The Input System fires a
performed event.
- Controller:
CharacterController receives the event, identifies the action ("Attack"), and checks its CurrentStateData.
- Mapping: It finds the associated
AttackActionData SO from the current state's mappings.
- Activation: It asks the
CharacterAction system to activate this action data, creating a RuntimeAction instance if needed.
- Action Logic: The
RuntimeAction checks CanActivate, performs Enter logic (plays animation, sets initial velocity), and becomes active.
- Update:
CharacterController calls Tick/FixedTick on the active RuntimeAction.
- Timing: The
RuntimeAction updates its timer, checks the AnimationTimingData, and tells the HitboxController to activate/deactivate specific hitboxes based on the timer/frame count.
- Finish: When the action's duration is over (timer exceeds duration),
FinishAction is called. It cleans up, deactivates hitboxes, and signals the CharacterController to potentially change state (e.g., back to Ground State).
This structure provides a decoupled, data-driven, and modular system. You can create new states and actions simply by creating new ScriptableObjects and configuring them, reusing the core CharacterController, RuntimeAction, IState, and ICharacterContext logic.