Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(Rigidbody))]
- public class playermotor : MonoBehaviour
- {
- [SerializeField]
- private Camera cam;
- private Vector3 velocity = Vector3.zero;
- private Vector3 rotation = Vector3.zero;
- private Vector3 verticalVelocity;
- private float cameraRotationX = 0f;
- private float currentCameraRotationX = 0f;
- [SerializeField]
- private Transform groundCheck;
- public float groundDistance = 0.4f;
- public LayerMask groundMask;
- bool isGrounded;
- [SerializeField]
- private float gravity = -9.8f;
- [SerializeField]
- private float cameraRotationLimit = 85f;
- private Rigidbody rb;
- void Start()
- {
- rb = GetComponent<Rigidbody>();
- }
- void Update()
- {
- verticalVelocity.y += gravity * Time.deltaTime;
- rb.MovePosition(rb.position + verticalVelocity * Time.deltaTime);
- isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
- if (isGrounded && velocity.y < 0)
- {
- verticalVelocity.y = -2f;
- }
- }
- // Gets a movement vector
- public void Move(Vector3 _velocity)
- {
- velocity = _velocity;
- }
- // Gets a rotational vector
- public void Rotate(Vector3 _rotation)
- {
- rotation = _rotation;
- }
- // Gets a rotational vector for the camera
- public void RotateCamera(float _cameraRotationX)
- {
- cameraRotationX = _cameraRotationX;
- }
- // Run physics
- void FixedUpdate()
- {
- PerformMovement();
- PerformRotation();
- }
- //Perform movement
- void PerformMovement()
- {
- if (velocity != Vector3.zero)
- {
- rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
- }
- }
- //Perform rotation
- void PerformRotation()
- {
- rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
- if (cam != null)
- {
- currentCameraRotationX -= cameraRotationX;
- currentCameraRotationX = Mathf.Clamp(currentCameraRotationX, -cameraRotationLimit, cameraRotationLimit);
- cam.transform.localEulerAngles = new Vector3(currentCameraRotationX, 0f, 0f);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement