In my game, I have one object that rotates around another using transform.RotateAround
, and I need to change the radius of its orbit.
The behavior now is that the orbiting object moves to the larger radius, but it also changes its height.
Both when running this code the first time or when changing the radius value at runtime, I want it to move to the new radius like it does now, but also to keep the current height.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateAroundPoint : MonoBehaviour
{
public Transform objectToRotateAround;
public Vector3 axis;
public float rotationSpeed;
public float moveToRadiusSpeed;
[SerializeField] private float radius;
private float lastRadius;
private void Start()
{
ApplyRadius();
}
private void Update()
{
if (!Mathf.Approximately(radius, lastRadius))
{
ApplyRadius();
}
transform.RotateAround(objectToRotateAround.position, axis, rotationSpeed * Time.deltaTime);
}
private void ApplyRadius()
{
Vector3 direction = (transform.position - objectToRotateAround.position).normalized;
Vector3 targetPosition = objectToRotateAround.position + direction * radius;
float step = moveToRadiusSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
if (Mathf.Abs(radius - lastRadius) < 0.001f)
{
transform.position = targetPosition;
lastRadius = radius;
}
}
}
I tried to change the code in the Update to this:
Vector3 direction = (transform.position - objectToRotateAround.position).normalized;
float currentDistance = Vector3.Distance(transform.position, objectToRotateAround.position);
float currentHeight = Mathf.Sqrt(Mathf.Pow(currentDistance, 2f) - Mathf.Pow(radius, 2f));
Vector3 newPosition = objectToRotateAround.position + direction * radius;
float step = moveToRadiusSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, newPosition + Vector3.up * currentHeight, step);
if (Mathf.Abs(radius - lastRadius) < 0.001f)
{
transform.position = newPosition + Vector3.up * currentHeight;
lastRadius = radius;
}
But this makes the orbiting object just to move up quickly and without stopping. It does rotate, but not around the target (objectToRotateAround
).