I added a dash function to my 2D player square a while ago and it worked just fine. However, the next day when working on my game it just stopped working after I put in a lot of code. What I’m trying to do is that when you press the Q key on your keyboard you basically get kicked forward in the direction your going to make it look like a dash. There will be a cooldown of 2 seconds for dashing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float moveHorizontal;
public float speed = 5f;
private Rigidbody2D rb;
public float jumpForce = 5f;
public float dashForce = 9000f;
private bool isJumping = false;
public Collider2D groundCollider;
private bool canDash = true;
public float dashCooldown = 2f;
private float lastDashTime = 0f;
public GameObject ZRotation;
void Start()
{
rb = GetComponent<Rigidbody2D>();
groundCollider = GetComponent<Collider2D>();
}
void Update()
{
ZRotation.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
moveHorizontal = Input.GetAxis("Horizontal");
Vector2 movement = new Vector2(moveHorizontal, 0f) * speed;
rb.velocity = new Vector2(movement.x, rb.velocity.y);
if (Input.GetButtonDown("Jump") && !isJumping)
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Impulse);
}
if (Input.GetKeyDown(KeyCode.Q) && canDash)
{
Dash();
Debug.Log("Q pressed");
}
// Sprinting Check!!!
if (Input.GetKey(KeyCode.LeftShift) && moveHorizontal != 0)
{
speed = 10f;
}
else
{
speed = 5f;
}
}
private void Dash()
{
Debug.Log("Dash Called");
Vector2 dashForceVector = new Vector2(moveHorizontal * dashForce, 0f);
rb.AddForce(dashForceVector, ForceMode2D.Impulse);
lastDashTime = Time.time;
canDash = false;
StartCoroutine(DashCooldown());
}
IEnumerator DashCooldown()
{
yield return new WaitForSeconds(dashCooldown);
canDash = true;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Floor"))
{
ContactPoint2D[] contacts = new ContactPoint2D[collision.contactCount];
collision.GetContacts(contacts);
foreach (ContactPoint2D contact in contacts)
{
Vector2 contactNormal = contact.normal;
float angle = Vector2.Angle(contactNormal, Vector2.up);
if (angle <= 45f)
{
isJumping = false;
break;
}
}
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Floor"))
{
isJumping = true;
}
}
}
This is my only script for my player square. It SHOULD be working. The debug logs are triggering and I’m not getting any errors but it’s not doing what I want it to. I have a feeling that it stopped working because I added a material to the square called Slip where it has 0 friction so that the player doesn’t stick to walls, but when I delete Slip the dash still doesn’t work, so I’m not really sure.