I Have Been trying all day to create a functional dash code. I’m almost there, but i keep encountering a bug where my dash happens sporadically, seemingly triggering randomly when i hit the corresponding button. sometimes it triggers, some times it doesn’t. i would appreciate any help on the topic.
Here is the code:
public class Player : MonoBehaviour
{
//Config
[SerializeField] float runSpeed = 5f;
[SerializeField] float dashSpeed = 15;
//States
bool isAlive = true;
//Cashed References
Rigidbody2D myRigidBody;
Animator myAnimator;
CapsuleCollider2D myBodyCollider;
// Methods and Messages
void Start()
{
myRigidBody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
myBodyCollider = GetComponent<CapsuleCollider2D>();
}
void Update()
{
Run();
FlipSprite();
}
private void Run()
{
float controlThrowHorizontal = Input.GetAxisRaw("Horizontal"); // value is betweeen -1 to +1
float controlThrowVertical = Input.GetAxisRaw("Vertical"); // value is betweeen -1 to +1
Vector2 playerVelocity = new Vector2(controlThrowHorizontal * runSpeed , controlThrowVertical*runSpeed );
myRigidBody.velocity = playerVelocity;
if (Input.GetKeyDown(KeyCode.Joystick1Button0) || Input.GetKeyDown("space"))
{
if(myRigidBody.velocity != new Vector2(0,0))
{
Debug.Log("space was pressed");
myRigidBody.velocity = playerVelocity * dashSpeed;
}
else
{
Debug.Log("dash from none");
playerVelocity = new Vector2(0, 5) * dashSpeed;
myRigidBody.velocity = playerVelocity;
}
}
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
bool playerHasVerticalSpeed = (myRigidBody.velocity.y) > Mathf.Epsilon;
bool playerHasNegativeVerticalSpeed = (myRigidBody.velocity.y) < -.01;
myAnimator.SetBool("isRunningDown", playerHasNegativeVerticalSpeed);
myAnimator.SetBool("isRunning", playerHasHorizontalSpeed);
myAnimator.SetBool("isRunningUp", playerHasVerticalSpeed);
}
private void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1);
}
}
}
*note: I am getting no errors of any kind.
Any help is appreciated.