PlayerMoveOnSphere.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Cinemachine.Utility;
  4. using UnityEngine;
  5. public class PlayerMoveOnSphere : MonoBehaviour
  6. {
  7. public SphereCollider Sphere;
  8. public float speed = 5;
  9. public bool rotatePlayer = true;
  10. public float rotationDamping = 0.5f;
  11. // Update is called once per frame
  12. void Update()
  13. {
  14. Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
  15. if (input.magnitude > 0)
  16. {
  17. input = Camera.main.transform.rotation * input;
  18. if (input.magnitude > 0.001f)
  19. {
  20. transform.position += input * (speed * Time.deltaTime);
  21. if (rotatePlayer)
  22. {
  23. float t = Cinemachine.Utility.Damper.Damp(1, rotationDamping, Time.deltaTime);
  24. Quaternion newRotation = Quaternion.LookRotation(input.normalized, transform.up);
  25. transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, t);
  26. }
  27. }
  28. }
  29. // Stick to sphere surface
  30. if (Sphere != null)
  31. {
  32. var up = transform.position - Sphere.transform.position;
  33. up = up.normalized;
  34. var fwd = transform.forward.ProjectOntoPlane(up);
  35. transform.position = Sphere.transform.position + up * (Sphere.radius + transform.localScale.y / 2);
  36. transform.rotation = Quaternion.LookRotation(fwd, up);
  37. }
  38. }
  39. }