I'm developing a map navigation system similar to Waze in Unity, and I have a recenter button and a camera that needs to smoothly position itself behind a target object when I press the button. I'm adjusting the camera's position and rotation using the touch and a recenter button. The process with the touch work's perfect, but I dont achieve a correct behavior of the recenter button to the camera aligns itself behind the target. I've attempted a few methods, but none seem to work as expected. Could someone provide guidance on how to calculate the rotation needed and gradually adjust the camera's position to achieve this effect?
When I press the recenter button the camera move's and stop's, but it does not end up in the correct position behind the target.
[SerializeField] Transform _Target;
[SerializeField] Button _reCenterButton;
[SerializeField] Vector3 _CameraOffset;
[SerializeField] float RotSpeed = 3f;
private bool isRecenter;
private float maxRotationAngle;
private bool isRotating = true;
private float accumulatedRotationAngle = 0.0f;
private void Start()
{
isRecenter = false;
_CameraOffset = transform.position - _Target.position;
_reCenterButton.onClick.AddListener(ReCenter);
}
private void LateUpdate()
{
camPosition();
}
private void ReCenter()
{
isRecenter = true;
isRotating = true;
accumulatedRotationAngle = 0.0f;
}
public void MaxRotationAngle()
{
Vector3 targetDirection = (_backTarget.position - transform.position).normalized;
float angleToRotate = Mathf.Acos(Vector3.Dot(_CameraOffset.normalized, targetDirection)) * Mathf.Rad2Deg;
maxRotationAngle = angleToRotate;
}
void camPosition()
{
if (Input.GetMouseButton(0))
{
Quaternion camturnAngle =
Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotSpeed, Vector3.up);
_CameraOffset = camturnAngle * _CameraOffset;
isRecenter = false;
}
else if (isRecenter)
{
if (isRotating)
{
Quaternion camturnAngle =
Quaternion.AngleAxis(0.84f * RotSpeed, Vector3.up);
_CameraOffset = camturnAngle * _CameraOffset;
accumulatedRotationAngle += Mathf.Abs(0.84f * RotSpeed);
Debug.Log(accumulatedRotationAngle);
Debug.Log(maxRotationAngle);
if (accumulatedRotationAngle >= maxRotationAngle)
{
isRotating = false;
}
}
}
SetCamPosition();
}
private void SetCamPosition()
{
Vector3 newPos = _Target.position + _CameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, smoothFactor);
transform.LookAt(_Target);
}