PlayerController.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using UnityEngine;
  3. public class PlayerController : MonoBehaviour
  4. {
  5. public Rigidbody rb;
  6. public float walkSpeed = 5f;
  7. public float runSpeed = 10f;
  8. public float rotateSpeed = 100f;
  9. public float jumpForce = 50f;
  10. public float stamina = 100f;
  11. public float drainRate = 20f;
  12. public bool bIsSprinting;
  13. public bool bCanSprint;
  14. public int health;
  15. public bool bHasBeenDamaged;
  16. private float currentSpeed;
  17. private bool bIsGrounded;
  18. private Vector2 input;
  19. void Update()
  20. {
  21. input.x = Input.GetAxis("Horizontal");
  22. input.y = Input.GetAxis("Vertical");
  23. bIsSprinting = Input.GetKey(KeyCode.LeftShift) && input.y > 0 && bCanSprint;
  24. currentSpeed = bIsSprinting ? runSpeed : walkSpeed;
  25. if (bIsSprinting)
  26. {
  27. stamina -= drainRate * Time.deltaTime;
  28. }
  29. stamina = Mathf.Clamp(stamina, 0, 100f);
  30. if (Input.GetButtonDown("Jump") && bIsGrounded)
  31. {
  32. Jump();
  33. }
  34. /*if (Input.GetKeyDown(KeyCode.F5))
  35. {
  36. GameManager.gameManagerInstance.SaveData();
  37. }*/
  38. }
  39. private void FixedUpdate()
  40. {
  41. Vector3 moveDirection = transform.forward * input.y * currentSpeed;
  42. rb.linearVelocity = new Vector3(moveDirection.x, rb.linearVelocity.y, moveDirection.z);
  43. float rotation = input.x * rotateSpeed * Time.fixedDeltaTime;
  44. transform.Rotate(0, rotation, 0);
  45. }
  46. private void Jump()
  47. {
  48. rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
  49. bIsGrounded = false;
  50. }
  51. public void ReduceHealth()
  52. {
  53. bHasBeenDamaged = true;
  54. health--;
  55. if(health <= 0)
  56. {
  57. Debug.Log("Player is dead");
  58. bHasBeenDamaged = false;
  59. }
  60. bHasBeenDamaged = false;
  61. }
  62. private void OnCollisionStay(Collision collision)
  63. {
  64. foreach (ContactPoint contact in collision.contacts)
  65. {
  66. if (contact.normal.y > 0.7f)
  67. {
  68. bIsGrounded = true;
  69. break;
  70. }
  71. }
  72. }
  73. private void OnCollisionExit(Collision collision)
  74. {
  75. bIsGrounded = false;
  76. }
  77. }