using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerMovement : MonoBehaviour { [SerializeField] float runSpeed = 10f; [SerializeField] float jumpSpeed = 5f; [SerializeField] GameObject swing; [SerializeField] Transform sword; [SerializeField] private float animationDuration = 1f; private bool isAttacking = false; Vector2 moveInput; Rigidbody2D myRigidbody; CapsuleCollider2D myBodyCollider; bool isAlive = true; Animator myAnimator; void Start() { myRigidbody = GetComponent(); myAnimator = GetComponent(); myBodyCollider = GetComponent(); } void Update() { if (Input.GetMouseButtonDown(0)) { StartCoroutine(Attack()); } if (!isAlive) { return; } Run(); Jump(); FlipSprite(); Die(); } private IEnumerator Attack() { isAttacking = true; myAnimator.SetBool("IsAttacking", true); // Wait for the animation to finish yield return new WaitForSeconds(animationDuration); myAnimator.SetBool("IsAttacking", false); isAttacking = false; } void OnFire(InputValue value) { if (!isAlive) { return; } Instantiate(swing, sword.position, transform.rotation); } void OnMove(InputValue value) { if (!isAlive) { return; } moveInput = value.Get(); } void OnJump(InputValue value) { if (!isAlive) { return; } if (!myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Ground"))) { return;} if(value.isPressed) { myRigidbody.velocity += new Vector2 (0f, jumpSpeed); } } void Jump() { bool playerHasVerticalSpeed = Mathf.Abs(myRigidbody.velocity.y) > Mathf.Epsilon; myAnimator.SetBool("IsJumping", playerHasVerticalSpeed); } void Run() { Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, myRigidbody.velocity.y); myRigidbody.velocity = playerVelocity; bool playerHasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon; myAnimator.SetBool("IsRunning", playerHasHorizontalSpeed); } void FlipSprite() { bool playerHasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon; if (playerHasHorizontalSpeed) { transform.localScale = new Vector2 (Mathf.Sign(myRigidbody.velocity.x), 1f); } } void Die() { if (myBodyCollider.IsTouchingLayers(LayerMask.GetMask("enemies" , "hazards"))) { isAlive = false; myAnimator.SetTrigger("Dying"); FindObjectOfType().ProcessPlayerDeath(); } } }