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!