Third Person Shooter (Unity Tutorial) Ep 3 Finite State Machines

4 min read 2 hours ago
Published on Oct 22, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will create a finite state machine (FSM) in Unity for a third-person shooter game. This will help manage different character animations, making your code more organized and easier to maintain. By the end of this guide, you will understand how to implement various character states such as idle, walking, running, and crouching, as well as how to transition between these states based on player input.

Step 1: Important Changes

Before diving into the FSM setup, ensure that you have made the following changes:

  • Verify that your animations from the previous tutorial are correctly imported and set up in Unity.
  • Ensure that your character's Animator Controller is assigned to the character model.

Step 2: Setting Up a Finite State Machine

To implement the FSM, follow these steps:

  1. Create a New Script:

    • Right-click in the Project panel, select Create > C# Script, and name it PlayerStateMachine.
  2. Define States:

    • Open the script and create an enum for the states:
    public enum PlayerState
    {
        Idle,
        Walking,
        Running,
        Crouching
    }
    
  3. Initialize Variables:

    • Add variables to hold the current state and animator reference:
    private PlayerState currentState;
    private Animator animator;
    
  4. Set Up Animator:

    • In the Start() method, get the Animator component:
    void Start()
    {
        animator = GetComponent<Animator>();
        currentState = PlayerState.Idle; // Start in idle state
    }
    

Step 3: Transitioning from the Idle State

Implement state transitions by creating a method to handle input and update states:

  1. Create an Update Method:

    • In the Update() method, determine the current state and check for input to transition:
    void Update()
    {
        switch (currentState)
        {
            case PlayerState.Idle:
                HandleIdleState();
                break;
            // Add more cases for other states
        }
    }
    
  2. Handle Idle State:

    • Create a method to manage input when in the idle state:
    void HandleIdleState()
    {
        if (Input.GetKey(KeyCode.W)) // Moving forward
        {
            TransitionToState(PlayerState.Walking);
        }
    }
    
  3. Transition Method:

    • Implement the transition logic:
    void TransitionToState(PlayerState newState)
    {
        currentState = newState;
        UpdateAnimatorParameters();
    }
    

Step 4: Setting Animator Parameters

Define parameters in the Animator to control animations based on the current state:

  1. Add Parameters in Animator:

    • Open the Animator window and add parameters like isWalking, isRunning, and isCrouching.
  2. Update Animator in Transition Method:

    • Modify the UpdateAnimatorParameters method to set these parameters based on the current state:
    void UpdateAnimatorParameters()
    {
        animator.SetBool("isWalking", currentState == PlayerState.Walking);
        animator.SetBool("isRunning", currentState == PlayerState.Running);
        animator.SetBool("isCrouching", currentState == PlayerState.Crouching);
    }
    

Step 5: Implementing Walking, Running, and Crouching States

Expand the FSM with additional states:

  1. Walking State:

    • Create a method to handle transitions into the walking state:
    void HandleWalkingState()
    {
        if (Input.GetKey(KeyCode.LeftShift)) // Check for running
        {
            TransitionToState(PlayerState.Running);
        }
        else if (Input.GetKey(KeyCode.S)) // Moving backward
        {
            TransitionToState(PlayerState.Idle);
        }
    }
    
  2. Running State:

    • Similarly, create logic for the running state:
    void HandleRunningState()
    {
        if (!Input.GetKey(KeyCode.LeftShift)) // Stop running
        {
            TransitionToState(PlayerState.Walking);
        }
    }
    
  3. Crouching State:

    • Handle crouching transitions:
    void HandleCrouchingState()
    {
        if (Input.GetKeyUp(KeyCode.C)) // Stand up
        {
            TransitionToState(PlayerState.Idle);
        }
    }
    

Step 6: Testing States and Animations

  1. Test in Unity:

    • Play the game in Unity and test the transitions between states.
    • Ensure the animations trigger correctly based on your input.
  2. Adjust Animator Settings:

    • If necessary, adjust the transitions in the Animator to make them smoother.

Step 7: Changing Speed Depending on State

Modify the character's movement speed based on the current state:

  1. Add Speed Variables:

    • Define float variables for each state speed:
    public float walkingSpeed = 2.0f;
    public float runningSpeed = 5.0f;
    
  2. Update Movement Logic:

    • Adjust the character's speed in the Update() method based on the current state.

Conclusion

In this tutorial, you learned how to implement a finite state machine in Unity for a third-person shooter game. You created a system to manage different character states, set animator parameters, and tested various transitions. As a next step, consider adding more complex behaviors or refining your animations further for a smoother gameplay experience. Happy coding!