Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. [RequireComponent(typeof(Rigidbody))]
  4. public class playermotor : MonoBehaviour
  5. {
  6. [SerializeField]
  7. private Camera cam;
  8.  
  9. private Vector3 velocity = Vector3.zero;
  10. private Vector3 rotation = Vector3.zero;
  11. private Vector3 verticalVelocity;
  12. private float cameraRotationX = 0f;
  13. private float currentCameraRotationX = 0f;
  14.  
  15. [SerializeField]
  16. private Transform groundCheck;
  17.  
  18. public float groundDistance = 0.4f;
  19. public LayerMask groundMask;
  20.  
  21. bool isGrounded;
  22.  
  23. [SerializeField]
  24. private float gravity = -9.8f;
  25.  
  26. [SerializeField]
  27. private float cameraRotationLimit = 85f;
  28.  
  29. private Rigidbody rb;
  30.  
  31. void Start()
  32. {
  33. rb = GetComponent<Rigidbody>();
  34. }
  35.  
  36. void Update()
  37. {
  38. verticalVelocity.y += gravity * Time.deltaTime;
  39. rb.MovePosition(rb.position + verticalVelocity * Time.deltaTime);
  40.  
  41. isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
  42.  
  43. if (isGrounded && velocity.y < 0)
  44. {
  45. verticalVelocity.y = -2f;
  46. }
  47. }
  48. // Gets a movement vector
  49. public void Move(Vector3 _velocity)
  50. {
  51. velocity = _velocity;
  52. }
  53.  
  54. // Gets a rotational vector
  55. public void Rotate(Vector3 _rotation)
  56. {
  57. rotation = _rotation;
  58. }
  59.  
  60. // Gets a rotational vector for the camera
  61. public void RotateCamera(float _cameraRotationX)
  62. {
  63. cameraRotationX = _cameraRotationX;
  64. }
  65.  
  66. // Run physics
  67. void FixedUpdate()
  68. {
  69. PerformMovement();
  70. PerformRotation();
  71. }
  72.  
  73. //Perform movement
  74. void PerformMovement()
  75. {
  76. if (velocity != Vector3.zero)
  77. {
  78. rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
  79. }
  80. }
  81.  
  82. //Perform rotation
  83. void PerformRotation()
  84. {
  85. rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
  86. if (cam != null)
  87. {
  88. currentCameraRotationX -= cameraRotationX;
  89. currentCameraRotationX = Mathf.Clamp(currentCameraRotationX, -cameraRotationLimit, cameraRotationLimit);
  90.  
  91. cam.transform.localEulerAngles = new Vector3(currentCameraRotationX, 0f, 0f);
  92. }
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement