quhluh

DASH CODE FOR A 2D GAME IN C#

Apr 1st, 2023
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.42 KB | None | 0 0
  1. public class PlayerController : MonoBehaviour
  2. {
  3.     public float dashSpeed = 10f; // the speed at which the player will dash
  4.     public float dashDuration = 0.5f; // the duration of the dash in seconds
  5.     public float dashCooldown = 1f; // the cooldown period between dashes in seconds
  6.  
  7.     private Rigidbody2D rb;
  8.     private bool isDashing = false; // flag to indicate if the player is currently dashing
  9.     private float dashTimeLeft = 0f; // the remaining duration of the dash
  10.     private float dashCooldownTimeLeft = 0f; // the remaining time until the player can dash again
  11.  
  12.     void Start()
  13.     {
  14.         rb = GetComponent<Rigidbody2D>();
  15.     }
  16.  
  17.     void Update()
  18.     {
  19.         // check if the player can dash
  20.         if (Input.GetKeyDown(KeyCode.Space) && !isDashing && dashCooldownTimeLeft <= 0f)
  21.         {
  22.             isDashing = true;
  23.             dashTimeLeft = dashDuration;
  24.             rb.velocity = transform.right * dashSpeed;
  25.         }
  26.  
  27.         // update the dash time and cooldown time
  28.         if (isDashing)
  29.         {
  30.             dashTimeLeft -= Time.deltaTime;
  31.             if (dashTimeLeft <= 0f)
  32.             {
  33.                 isDashing = false;
  34.                 dashCooldownTimeLeft = dashCooldown;
  35.                 rb.velocity = Vector2.zero;
  36.             }
  37.         }
  38.         else if (dashCooldownTimeLeft > 0f)
  39.         {
  40.             dashCooldownTimeLeft -= Time.deltaTime;
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment