PlayerController.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. public Transform groundCheck;
  19. public float groundDistance = 0.2f;
  20. public LayerMask groundMask;
  21. private Vector2 input;
  22. void Update()
  23. {
  24. input.x = Input.GetAxis("Horizontal");
  25. input.y = Input.GetAxis("Vertical");
  26. bIsSprinting = Input.GetKey(KeyCode.LeftShift) && input.y > 0 && bCanSprint;
  27. currentSpeed = bIsSprinting ? runSpeed : walkSpeed;
  28. if (bIsSprinting)
  29. {
  30. stamina -= drainRate * Time.deltaTime;
  31. }
  32. stamina = Mathf.Clamp(stamina, 0, 100f);
  33. bIsGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
  34. if (Input.GetButtonDown("Jump") && bIsGrounded)
  35. {
  36. Jump();
  37. }
  38. /*if (Input.GetKeyDown(KeyCode.F5))
  39. {
  40. GameManager.gameManagerInstance.SaveData();
  41. }*/
  42. }
  43. private void FixedUpdate()
  44. {
  45. Vector3 moveDirection = transform.forward * input.y * currentSpeed;
  46. rb.linearVelocity = new Vector3(moveDirection.x, rb.linearVelocity.y, moveDirection.z);
  47. float rotation = input.x * rotateSpeed * Time.fixedDeltaTime;
  48. transform.Rotate(0, rotation, 0);
  49. }
  50. private void Jump()
  51. {
  52. rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
  53. bIsGrounded = false;
  54. }
  55. public void ReduceHealth()
  56. {
  57. bHasBeenDamaged = true;
  58. health--;
  59. if(health <= 0)
  60. {
  61. Debug.Log("Player is dead");
  62. bHasBeenDamaged = false;
  63. }
  64. bHasBeenDamaged = false;
  65. }
  66. }