Movement.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Movement : MonoBehaviour {
  5. CharacterController mController;
  6. Vector3 velocity;
  7. public float Gravity;
  8. public float moveSpeed;
  9. public float jumpHeight=10;
  10. public float lookSensitivity;
  11. Camera cam;
  12. Vector3 rot;
  13. float defaultHeight;
  14. public float crouchHeight;
  15. public float crouchSpeed;
  16. bool crouch=true;
  17. public enum myEnum
  18. {
  19. hold,
  20. toggle
  21. };
  22. public myEnum crouchType;
  23. // Use this for initialization
  24. void Start () {
  25. mController = GetComponent<CharacterController>();
  26. cam = GetComponentInChildren<Camera>();
  27. defaultHeight = mController.height;
  28. }
  29. // Update is called once per frame
  30. void Update () {
  31. Move();
  32. GravityControl();
  33. //Jump();
  34. Crouch();
  35. }
  36. private void Move()
  37. {
  38. if (Input.GetKey(KeyCode.W))
  39. mController.Move(transform.forward*moveSpeed*Time.deltaTime);
  40. if (Input.GetKey(KeyCode.S))
  41. mController.Move(-transform.forward * moveSpeed * Time.deltaTime);
  42. if (Input.GetKey(KeyCode.A))
  43. mController.Move(-transform.right * moveSpeed * Time.deltaTime);
  44. if (Input.GetKey(KeyCode.D))
  45. mController.Move(transform.right * moveSpeed * Time.deltaTime);
  46. }
  47. void GravityControl()
  48. {
  49. if (!mController.isGrounded)
  50. {
  51. velocity.y += Gravity * Time.deltaTime;
  52. }
  53. mController.Move(velocity * Time.deltaTime);
  54. }
  55. void Jump()
  56. {
  57. /*if (Input.GetKeyDown(KeyCode.Space)&&mController.isGrounded)
  58. {
  59. velocity.y += jumpHeight * Time.deltaTime;
  60. }*/
  61. }
  62. void Crouch()
  63. {
  64. if (crouchType.ToString()=="hold")
  65. {
  66. if (Input.GetKey(KeyCode.C))
  67. {
  68. mController.height = Mathf.Lerp(mController.height, crouchHeight, crouchSpeed * Time.deltaTime);
  69. }
  70. else
  71. {
  72. mController.height = Mathf.Lerp(mController.height, defaultHeight, crouchSpeed * Time.deltaTime);
  73. }
  74. }
  75. if (crouchType.ToString() == "toggle")
  76. {
  77. if (Input.GetKeyDown(KeyCode.C))
  78. {
  79. crouch = !crouch;
  80. }
  81. if (crouch)
  82. {
  83. mController.height = Mathf.Lerp(mController.height,crouchHeight,crouchSpeed*Time.deltaTime);
  84. }
  85. else
  86. {
  87. mController.height = Mathf.Lerp(mController.height, defaultHeight, crouchSpeed * Time.deltaTime);
  88. }
  89. }
  90. }
  91. }