Guest User

Untitled

a guest
Sep 25th, 2023
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. public class Rotation : MonoBehaviour
  5. {
  6. Quaternion[] rotations;
  7.  
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. Vector3 start = transform.position;
  12. Vector3 end = new Vector3(10, 0, 10);
  13. Quaternion endRot = Quaternion.identity;
  14. rotations = CalculateRotations(start, end, endRot, 0.1f);
  15. transform.rotation = rotations[0];
  16. StartCoroutine(Move(start, end));
  17. }
  18.  
  19. IEnumerator Move(Vector3 startPosition, Vector3 endPosition)
  20. {
  21. Vector3 direction = (endPosition - startPosition).normalized;
  22. for (int i = 1; i < rotations.Length; i++)
  23. {
  24. float step = 0.01f;
  25. float t = 0.01f;
  26. Quaternion start = rotations[i - 1];
  27. Quaternion end = rotations[i];
  28. while (t <= 1)
  29. {
  30. transform.position = Vector3.Lerp(startPosition, startPosition+direction, t);
  31. transform.rotation = Quaternion.Lerp(start, end, t);
  32. t += step;
  33. yield return null;
  34. }
  35. startPosition = transform.position;
  36. }
  37. }
  38. public Quaternion[] CalculateRotations(Vector3 startPosition, Vector3 endPosition, Quaternion endRotation, float ballRadius)
  39. {
  40. float distance = Vector3.Distance(startPosition, endPosition);
  41. float circumference = 2 * Mathf.PI * ballRadius;
  42. float revolutions = distance / circumference;
  43.  
  44. Quaternion[] rotations = new Quaternion[Mathf.CeilToInt(distance)];
  45.  
  46. //Debug.Log(revolutions); //I added this to debug, this wasn't chatgpt's doing
  47.  
  48. Vector3 direction = endPosition - startPosition;
  49. Vector3 axisOfRotation = Vector3.Cross(Vector3.up, direction).normalized;
  50. if (Vector3.Dot(Vector3.up, direction) < 0)
  51. {
  52. axisOfRotation *= -1; // Reverse the axis if needed
  53. }
  54.  
  55. rotations[0] = Quaternion.AngleAxis(revolutions * 360f, axisOfRotation) * endRotation;
  56.  
  57. float travelled = 1f / circumference;
  58.  
  59. for (int i = 1; i < Mathf.FloorToInt(distance); i++)
  60. {
  61. rotations[i] = Quaternion.AngleAxis(i * travelled * 360f, axisOfRotation);
  62. }
  63. rotations[rotations.Length - 1] = endRotation;
  64. return rotations;
  65. }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment