using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private float horizontal; private float speed = 8f; private float jumpingPower = 16f; private bool isFacingRight = true; private bool canJump = true; // To manage jump cooldown private bool isJumping = false; // To manage jump animation state public bool isAlive = true; [SerializeField] private Rigidbody2D rb; [SerializeField] private Transform groundCheck; [SerializeField] private LayerMask groundLayer; Animator myAnimator; void Start() { myAnimator = GetComponent(); Time.timeScale = 1f; } private void Update() { if (!isAlive) { myAnimator.SetBool("IsWalking", false); myAnimator.SetBool("IsDead", true); return; } Run(); // Calling the run function Jump(); // Calling the jump function Flip(); // Calling the flip function } private void Run() // Function for running and animation { horizontal = Input.GetAxisRaw("Horizontal"); if (isJumping) { myAnimator.SetBool("IsWalking", false); } else { if (rb.velocity.x != 0) { myAnimator.SetBool("IsWalking", true); } else { myAnimator.SetBool("IsWalking", false); } } } private void Jump() // Function for jumping { if (!isAlive) return; if (Input.GetButtonDown("Jump") && IsGrounded() && canJump) { rb.velocity = new Vector2(rb.velocity.x, jumpingPower); myAnimator.SetBool("IsJumping", true); isJumping = true; StartCoroutine(JumpCooldown()); StartCoroutine(HandleJumpAnimation()); } if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f) { rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f); } } private void FixedUpdate() { rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); } private bool IsGrounded() // Checks that the player is grounded { return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer); } private void Flip() // Flips the players sprite to the way it should be facing { if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f) { Vector3 localScale = transform.localScale; isFacingRight = !isFacingRight; localScale.x *= -1f; transform.localScale = localScale; } } private IEnumerator JumpCooldown() // Jump cooldown { canJump = false; yield return new WaitForSeconds(0.2f); canJump = true; } private IEnumerator HandleJumpAnimation() // Makes sure that the jump animation plays for an appropriate amount of time { yield return new WaitForSeconds(0.1f); // Add a slight delay to prevent immediate reset yield return new WaitForSeconds(0.5f); // Ensure jump animation duration myAnimator.SetBool("IsJumping", false); isJumping = false; } }