Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using UnityEngine;
- public class Rotation : MonoBehaviour
- {
- Quaternion[] rotations;
- // Start is called before the first frame update
- void Start()
- {
- Vector3 start = transform.position;
- Vector3 end = new Vector3(10, 0, 10);
- Quaternion endRot = Quaternion.identity;
- rotations = CalculateRotations(start, end, endRot, 0.1f);
- transform.rotation = rotations[0];
- StartCoroutine(Move(start, end));
- }
- IEnumerator Move(Vector3 startPosition, Vector3 endPosition)
- {
- Vector3 direction = (endPosition - startPosition).normalized;
- for (int i = 1; i < rotations.Length; i++)
- {
- float step = 0.01f;
- float t = 0.01f;
- Quaternion start = rotations[i - 1];
- Quaternion end = rotations[i];
- while (t <= 1)
- {
- transform.position = Vector3.Lerp(startPosition, startPosition+direction, t);
- transform.rotation = Quaternion.Lerp(start, end, t);
- t += step;
- yield return null;
- }
- startPosition = transform.position;
- }
- }
- public Quaternion[] CalculateRotations(Vector3 startPosition, Vector3 endPosition, Quaternion endRotation, float ballRadius)
- {
- float distance = Vector3.Distance(startPosition, endPosition);
- float circumference = 2 * Mathf.PI * ballRadius;
- float revolutions = distance / circumference;
- Quaternion[] rotations = new Quaternion[Mathf.CeilToInt(distance)];
- //Debug.Log(revolutions); //I added this to debug, this wasn't chatgpt's doing
- Vector3 direction = endPosition - startPosition;
- Vector3 axisOfRotation = Vector3.Cross(Vector3.up, direction).normalized;
- if (Vector3.Dot(Vector3.up, direction) < 0)
- {
- axisOfRotation *= -1; // Reverse the axis if needed
- }
- rotations[0] = Quaternion.AngleAxis(revolutions * 360f, axisOfRotation) * endRotation;
- float travelled = 1f / circumference;
- for (int i = 1; i < Mathf.FloorToInt(distance); i++)
- {
- rotations[i] = Quaternion.AngleAxis(i * travelled * 360f, axisOfRotation);
- }
- rotations[rotations.Length - 1] = endRotation;
- return rotations;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment