Forum begins after the advertisement:


[General] Adding Dash Mechanics and Character Abilities

Home › Forums › Video Game Tutorial Series › Creating a Rogue-like Shoot-em Up in Unity › [General] Adding Dash Mechanics and Character Abilities

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #20163
    Chelsea
    Level 5
    Moderator
    Helpful?
    Up
    0
    ::

    This is in response to @CarryEmiya’s question on YouTube:

    what if i want to add more moves like dash and abilities do i just add more codes in the same place with my normal movement code and everything would work the same or does this method work only for this type of movement system

    @rogu.apustaja Can you show us how to expand the existing PlayerMovement script by implementing a working dash mechanic that integrates with the current movement system. Explain how additional movement mechanics can be added to the existing script without interfering with normal movement.

    #20166
    Rogu Apustaja
    Level 2
    AI Reply Bot
    Helpful?
    Up
    0
    ::

    Hey Chelsea! Get ready to level up your player controller! We are going to blitz through these mechanics and upgrade your movement system wave by wave. You’ve got a massive vision for your game, and we are going to lock down the exact code and architecture you need to conquer it!

    Let’s tackle this challenge in three distinct waves!


    ⚡ WAVE 1: Deploying the Dash Mechanic

    To get a snappy, responsive dash running inside your PlayerMovement script, we are going to use a Coroutine. This lets us temporarily override your normal walking speed and manage cooldown timers cleanly without bogging down your Update() loop!

    Here is the upgraded PlayerMovement.cs script:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class PlayerMovement : MonoBehaviour
    {
        // Movement Variables (Existing)
        public const float DEFAULT_MOVESPEED = 5f;
        [HideInInspector] public Vector2 moveDir;
        [HideInInspector] public float lastHorizontalVector;
        [HideInInspector] public float lastVerticalVector;
        [HideInInspector] public Vector2 lastMovedVector;
    
        // Dash Variables (New!)
        [Header("Dash Settings")]
        public float dashSpeedMultiplier = 2.5f; // Speed boost during dash
        public float dashDuration = 0.2f;        // How long the dash lasts
        public float dashCooldown = 1.0f;        // Time before next dash
        private bool canDash = true;
        private bool isDashing = false;
    
        // References
        Rigidbody2D rb;
        PlayerStats playerStats; 
    
        void Start()
        {
            rb = GetComponent();
            playerStats = GetComponent();
            lastMovedVector = new Vector2(1, 0f); 
        }
    
        void Update()
        {
            InputManagement();
    
            // Trigger the Dash!
            if (Input.GetKeyDown(KeyCode.Space) && canDash && !isDashing)
            {
                StartCoroutine(Dash());
            }
        }
    
        void FixedUpdate()
        {
            Move();
        }
    
        void InputManagement()
        {
            float moveX = Input.GetAxisRaw("Horizontal");
            float moveY = Input.GetAxisRaw("Vertical");
    
            moveDir = new Vector2(moveX, moveY).normalized;
    
            if (moveDir.x != 0)
            {
                lastHorizontalVector = moveDir.x;
                lastMovedVector = new Vector2(lastHorizontalVector, 0f);
            }
            if (moveDir.y != 0)
            {
                lastVerticalVector = moveDir.y;
                lastMovedVector = new Vector2(0f, lastVerticalVector);
            }
            if (moveDir.x != 0 && moveDir.y != 0)
            {
                lastMovedVector = new Vector2(lastHorizontalVector, lastVerticalVector);
            }
        }
    
        void Move()
        {
            float currentMoveSpeed = playerStats != null ? playerStats.MoveSpeed : DEFAULT_MOVESPEED;
    
            if (isDashing)
            {
                // Blast the player forward in their current or last known direction!
                Vector2 dashDirection = (moveDir != Vector2.zero) ? moveDir : lastMovedVector;
                rb.velocity = dashDirection.normalized * currentMoveSpeed * dashSpeedMultiplier;
            }
            else
            {
                // Standard movement
                rb.velocity = moveDir * currentMoveSpeed;
            }
        }
    
        IEnumerator Dash()
        {
            canDash = false;
            isDashing = true;
    
            // Hold the dash state for the set duration
            yield return new WaitForSeconds(dashDuration);
    
            isDashing = false;
    
            // Wait for the cooldown before re-enabling the dash
            yield return new WaitForSeconds(dashCooldown);
    
            canDash = true;
        }
    }

    How this code clears the wave:

    • The Variables: dashSpeedMultiplier, dashDuration, and dashCooldown give you total control right in the Unity Inspector! canDash and isDashing act as our gatekeepers.
    • The Trigger: Inside Update(), pressing Space checks both booleans. If you are good to go, it launches the Dash() coroutine!
    • The Coroutine: Dash() flips isDashing to true, waits using WaitForSeconds(dashDuration), flips it back to false so normal movement resumes, and then runs the cooldown timer before letting you dash again.
    • Smart Direction Debugging: Notice the dashDirection check inside Move()! If you stop moving and press dash, moveDir is zero. By falling back on lastMovedVector, you ensure your player always dashes in the direction they are facing instead of getting stuck in place. Spot-on execution!

    🛡️ WAVE 2: Scaling Up Without Interference (State Machines!)

    If you want to add even more awesome mechanics later—like sliding, hovering, or knockback—stacking if/else statements with booleans (isSliding, isHovering, isStunned) will quickly tangle up your script.

    To keep your code laser-focused and bug-free, you can upgrade to a State Machine Pattern using an enum:

    • Step 1: Define Your States: Create an enum at the top of your script to hold every possible movement mode.

      public enum MovementState { Normal, Dashing, Hovering, Stunned }
      public MovementState currentState = MovementState.Normal;
    • Step 2: Switch States in Coroutines/Inputs: Instead of flipping multiple booleans, your Dash() coroutine simply changes currentState = MovementState.Dashing;, and sets it back to MovementState.Normal when finished!

    • Step 3: Route Physics Through a Switch Statement: Inside Move(), replace the if/else block with a clean switch statement:

      void Move()
      {
          float currentMoveSpeed = playerStats != null ? playerStats.MoveSpeed : DEFAULT_MOVESPEED;
      
          switch (currentState)
          {
              case MovementState.Normal:
                  rb.velocity = moveDir * currentMoveSpeed;
                  break;
      
              case MovementState.Dashing:
                  Vector2 dashDirection = (moveDir != Vector2.zero) ? moveDir : lastMovedVector;
                  rb.velocity = dashDirection.normalized * currentMoveSpeed * dashSpeedMultiplier;
                  break;
      
              case MovementState.Stunned:
                  rb.velocity = Vector2.zero; // Freeze player cleanly!
                  break;
          }
      }
    • Why This Rocks for Debugging: Because currentState can only hold one value at a time, mechanics will never fight each other for control of the Rigidbody2D.velocity! If a bug ever pops up, you just look at what state the player is currently locked into, and you’ll find the culprit instantly.


    🚀 WAVE 3: The Boss Level — Character-Specific Abilities

    Adding unique, character-specific abilities (like casting fireballs, deploying shields, or triggering character-exclusive buffs) is a massive leap in complexity compared to universal movement mechanics!

    Here is how you want to approach this system:

    • Keep PlayerMovement Clean: Trying to hardcode unique character powers directly into PlayerMovement will make that script overloaded and very hard to maintain. Your movement script should only ever care about moving the character!
    • Build a Dedicated Ability System: To manage different abilities across a roster of characters, you need a separate, modular architecture. This usually involves:
      • Ability ScriptableObjects: Creating data assets for each ability that store their own cooldowns, effects, and activation logic.
      • An Ability Manager Component: A separate script attached to the player that reads which character you picked, loads their specific Ability ScriptableObjects, and listens for ability button presses.
    • Your Next Mission (Hit Part 20!): Before diving into building a custom ability manager from scratch, I highly recommend pushing forward and following the tutorial series up to approximately Part 20!
      • As you progress toward Part 20, you will unlock crucial architectural patterns—like advanced ScriptableObject data management, passive/weapon controllers, and how PlayerStats dynamically interacts with external systems.
      • Mastering the way the series structures weapons and passives first will give you the exact blueprint you need to build a custom ability system with zero guesswork!

    Keep up this incredible momentum, Chelsea! Drop that dash code into Unity, take it for a spin, and let us know how it feels!

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: