Enderlook

Player Rotation

Apr 8th, 2021
487
352 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.         private Vector2 currentRotation;
  2.         private Vector2 targetRotation;
  3.         private Vector2 lastFrameRotation;
  4.         private void Rotate()
  5.         {
  6.             if (Cursor.lockState == CursorLockMode.Locked)
  7.             {
  8.                 Cursor.lockState = CursorLockMode.Confined;
  9.                 lastFrameRotation = Remap(Camera.main.ScreenToViewportPoint(Input.mousePosition));
  10.             }
  11.  
  12.             Vector2 mousePosition = Remap(Camera.main.ScreenToViewportPoint(Input.mousePosition));
  13.             Vector2 difference = mousePosition - lastFrameRotation;
  14.             lastFrameRotation = mousePosition;
  15.             targetRotation += difference;
  16.             targetRotation = new Vector2(Mathf.Clamp(targetRotation.x, -maximumVerticalAngle, maximumVerticalAngle), targetRotation.y);
  17.  
  18.             if (mousePosition.y < 5 || mousePosition.y > 355)
  19.                 Cursor.lockState = CursorLockMode.Locked;
  20.  
  21.             if (rotationSpeed > 0)
  22.                 currentRotation = Vector3.MoveTowards(currentRotation, targetRotation, rotationSpeed);
  23.             else
  24.                 currentRotation = targetRotation;
  25.  
  26.             Quaternion xQ = Quaternion.AngleAxis(currentRotation.x, Vector3.left);
  27.             Quaternion yQ = Quaternion.AngleAxis(currentRotation.y, Vector3.up);
  28.  
  29.             if (smoothRotation > 0)
  30.             {
  31.                 // Horizontal rotation is applied on the player body.
  32.                 rigidbody.rotation = Quaternion.Lerp(rigidbody.rotation, yQ, Time.fixedDeltaTime * smoothRotation);
  33.                 // Vertical rotation is only applied on the player head.
  34.                 head.transform.localRotation = Quaternion.Lerp(head.transform.localRotation, xQ, Time.fixedDeltaTime * smoothRotation);
  35.             }
  36.             else
  37.             {
  38.                 // Horizontal rotation is applied on the player body.
  39.                 rigidbody.rotation = yQ;
  40.                 // Vertical rotation is only applied on the player head.
  41.                 head.transform.localRotation = xQ;
  42.             }
  43.  
  44.             Vector2 Remap(Vector3 value) => new Vector2((value.y - .5f) * maximumVerticalAngle, value.x * 360);
  45.         }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×