SamsonGame/Assets/Scripts/Managers/Camera/CameraTargetFollower.cs

68 lines
1.9 KiB
C#

using UnityEngine;
namespace RND
{
public class CameraTargetFollower : MonoBehaviour
{
[SerializeField, ReadOnly]private Transform _targetTransform;
private bool _isFollow;
private NullableVector3 _overwrites = new NullableVector3();
public Transform GetTarget() => _targetTransform;
public static CameraTargetFollower CreateTarget()
{
var target = new GameObject("TargetFollow");
var follower = target.AddComponent<CameraTargetFollower>();
return follower;
}
public void SetTarget(Transform target, bool instantTransition, NullableVector3 overwrites)
{
_targetTransform = target;
if(instantTransition)
transform.SetPositionAndRotation(
target.transform.position,
Quaternion.LookRotation(target.forward)
);
if(overwrites != null)
_overwrites = overwrites;
_isFollow = true;
}
public void ResetTarget()
{
_targetTransform = null;
_overwrites = new NullableVector3();
_isFollow = false;
}
private void FixedUpdate()
{
if (_targetTransform == null || !_isFollow)
return;
UpdateTargetPosition();
}
private void UpdateTargetPosition()
{
transform.SetPositionAndRotation(
Vector3.MoveTowards(
transform.position,
new Vector3(
_overwrites.X ?? _targetTransform.position.x,
_overwrites.Y ?? _targetTransform.position.y,
_overwrites.Z ?? _targetTransform.position.z),
Time.fixedDeltaTime * 30f
),
Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(_targetTransform.forward),
Time.fixedDeltaTime * 30f)
);
}
}
}