48 lines
1.2 KiB
C#
48 lines
1.2 KiB
C#
using UnityEngine;
|
|
|
|
public class CameraTargetFollower : MonoBehaviour
|
|
{
|
|
private Transform _targetTransform;
|
|
private bool _isFollow;
|
|
|
|
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 = false)
|
|
{
|
|
_targetTransform = target;
|
|
|
|
if(instantTransition)
|
|
transform.SetPositionAndRotation(
|
|
target.transform.position,
|
|
Quaternion.LookRotation(target.forward)
|
|
);
|
|
|
|
_isFollow = true;
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
if (_targetTransform == null || !_isFollow)
|
|
return;
|
|
|
|
UpdateTargetPosition();
|
|
}
|
|
|
|
private void UpdateTargetPosition()
|
|
{
|
|
transform.SetPositionAndRotation(
|
|
Vector3.MoveTowards(transform.position, _targetTransform.position, Time.fixedDeltaTime * 30f),
|
|
Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(_targetTransform.forward),
|
|
Time.fixedDeltaTime * 30f)
|
|
);
|
|
}
|
|
}
|
|
|