- Home /
Able to dash in the air but NOT on the floor/standing tile
Hi guys,
I am implementing game mechanics to my character and for some reason I am not able to dash while moving right/left but while I am in the air/jumping, I am able to dash left or right. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlienController : MonoBehaviour
{
float horizontalMovement;
[SerializeField]
float jumpForce = 500f, moveSpeed = 5f;
Rigidbody2D rb;
bool doubleJumpAllowed = true;
bool onTheGround = true;
bool isDashing = false;
float dashCooldown;
void Start () {
rb = GetComponent<Rigidbody2D> ();
}
void Update () {
if(onTheGround)
isDashing = false;
if(Input.GetKeyDown(KeyCode.X) && !isDashing && !onTheGround)
{
StartCoroutine(Dash());
}
//Jump Logic
if (onTheGround && Input.GetButtonDown ("Jump"))
{
Jump();
onTheGround = false;
}
else if (doubleJumpAllowed && Input.GetButtonDown ("Jump"))
{
Jump();
doubleJumpAllowed = false;
}
horizontalMovement = Input.GetAxis ("Horizontal") * moveSpeed;
}
void FixedUpdate()
{
if(!isDashing)
rb.velocity = new Vector2 (horizontalMovement, rb.velocity.y);
}
void OnCollisionEnter2D()
{
onTheGround = true;
doubleJumpAllowed = true;
isDashing = false;
}
IEnumerator Dash()
{
isDashing = true;
rb.velocity = new Vector2(Input.GetAxis ("Horizontal") * 15f, 0f);
var gravity = rb.gravityScale;
rb.gravityScale = 0;
yield return new WaitForSeconds(0.5f);
rb.gravityScale = gravity;
}
void Jump()
{
rb.velocity = new Vector2 (rb.velocity.x, 0f);
rb.AddForce(Vector2.up * jumpForce);
}
}
If anyone is able to help me dash left/right while not jumping, I would be very grateful!
Thanks and have a wonderful day!
Answer by zhavens88 · Sep 12, 2021 at 08:20 AM
Hello, i think you want !isGrounded to be isGrounded on your X button keycheck. you have..
if(Input.GetKeyDown(KeyCode.X) && !isDashing && !onTheGround)
Basically you've said "if im not dashing and NOT on the ground, Then dash.
Should be
if(Input.GetKeyDown(KeyCode.X) && !isDashing && isGrounded)
"if im not dashing and im ON the ground"
im no pro so hopefully that helps. i cant tell if anything else is wrong ( it all looks pretty good though)
Thanks mate, that fixed it for me! Can't believe I didn't see that since it is pretty obvious when you laid out.