Hero.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.SceneManagement;
  5. using UnityEngine.Tilemaps;
  6. public class Hero : MonoBehaviour
  7. {
  8. public float m_MoveSpeed;
  9. public Animator animator;
  10. Rigidbody2D rb;
  11. public enum PlayerState { Alive, Dead }
  12. public PlayerState playerState = PlayerState.Alive;
  13. public Vector2 lookFacing;
  14. public Vector2 respawnPoint;
  15. AudioSource audioSource;
  16. float dashCooldown = 0f;
  17. public bool dead = false;
  18. void Start() {
  19. rb = GetComponent<Rigidbody2D>();
  20. animator.SetBool("alive", true);
  21. audioSource = GetComponent<AudioSource>();
  22. }
  23. void Update ()
  24. {
  25. if(playerState == PlayerState.Dead) {
  26. rb.velocity = Vector2.zero;
  27. return;
  28. }
  29. Vector3 tryMove = Vector3.zero;
  30. if (Input.GetKey(KeyCode.LeftArrow))
  31. tryMove += Vector3Int.left;
  32. if (Input.GetKey(KeyCode.RightArrow))
  33. tryMove += Vector3Int.right;
  34. if (Input.GetKey(KeyCode.UpArrow))
  35. tryMove += Vector3Int.up;
  36. if (Input.GetKey(KeyCode.DownArrow))
  37. tryMove += Vector3Int.down;
  38. rb.velocity = Vector3.ClampMagnitude(tryMove, 1f) * m_MoveSpeed;
  39. animator.SetBool("moving", tryMove.magnitude > 0);
  40. if (Mathf.Abs(tryMove.x) > 0) {
  41. animator.transform.localScale = tryMove.x < 0f ? new Vector3(-1f, 1f, 1f) : new Vector3(1f, 1f, 1f);
  42. }
  43. if(tryMove.magnitude > 0f) {
  44. lookFacing = tryMove;
  45. }
  46. dashCooldown = Mathf.MoveTowards(dashCooldown, 0f, Time.deltaTime);
  47. if (Input.GetButtonDown("Jump")) {
  48. if(dashCooldown <= 0f && tryMove.magnitude > 0) {
  49. var hit = Physics2D.Raycast(transform.position + Vector3.up * .5f, tryMove.normalized, 3.5f, 1 << LayerMask.NameToLayer("Wall"));
  50. float distance = 3f;
  51. if(hit.collider != null) {
  52. distance = hit.distance - .5f;
  53. }
  54. transform.position = rb.position + Vector2.ClampMagnitude(tryMove, 1f) * distance;
  55. if (audioSource != null) audioSource.Play();
  56. }
  57. }
  58. animator.SetBool("dash_ready", dashCooldown <= 0f);
  59. }
  60. public void LevelComplete() {
  61. Destroy(gameObject);
  62. }
  63. }