Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

using System.

Collections;
using UnityEngine;

public class PlayerMovement : MonoBehaviour


{
[SerializeField] private float speed;
[SerializeField] private float dashSpeed;
private Rigidbody2D body;
private Animator anim;
private bool grounded;
private bool dash;

private void Awake()


{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}

private void Update()


{
float horizontalInput = Input.GetAxis("Horizontal");

if (Input.GetKeyDown(KeyCode.E) && !dash)


StartCoroutine(Dash());

if (!dash)
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

if (horizontalInput > 0.01f)


transform.localScale = Vector2.one;
else if (horizontalInput < -0.01f)
transform.localScale = new Vector3(-1, 1, 1);

if (Input.GetKeyDown(KeyCode.Space) && grounded)


body.velocity = new Vector2(body.velocity.x, speed);

anim.SetBool("run", Mathf.Abs(horizontalInput) > 0.01f);


anim.SetBool("grounded", grounded);
anim.SetBool("dash", dash);
}

private IEnumerator Dash()


{
dash = true;
float dashDuration = 0.3f;

body.velocity = new Vector2(transform.localScale.x * dashSpeed,


body.velocity.y);

anim.SetTrigger("dash");

yield return new WaitForSeconds(dashDuration);


dash = false;
}

private void OnCollisionEnter2D(Collision2D collision)


{
if (collision.gameObject.CompareTag("Ground"))
grounded = true;
}

private void OnCollisionExit2D(Collision2D collision)


{
if (collision.gameObject.CompareTag("Ground"))
grounded = false;
}
}

You might also like