2dCamera跟随
原理
判断当前角色位置与Camera位置是否超过偏移值 超过偏移值则插值设置位置
源码:
public class CameraToPlayer : MonoBehaviour
{
private Transform player;
private Vector2 GoPos;
[Tooltip("摄像头平滑移动速度")]
public float Speed;
[Tooltip("允许偏移的值")]
public float OffsetX;//X方向坐标超出当前值进行跟随
public float OffsetY;
[Header("限制镜头移动范围 防止背景超出")]
[Tooltip("最大的位置 x坐标")]
public Vector2 MaxPos;
[Tooltip("最小的位置Y坐标")]
public Vector2 MinPos;
//通过最大最小两点构成一个长方形范围 进行限制camera移动防止背景超出
private void Start()
{
player = GameObject.Find("Player").transform;
}
private void Update()
{
Floow();
}
public void Floow()
{
var position = transform.position;
var position1 = player.position;
GoPos = new Vector2(
Mathf.Abs(position.x - position1.x) > OffsetX ? Mathf.Lerp(position.x, position1.x, Speed) : position.x,
Mathf.Abs(position.y - position1.y) > OffsetY ? Mathf.Lerp(position.y, position1.y, Speed) : position.y);
float X = GoPos.x;
float Y = GoPos.y;
X = Mathf.Clamp(X, MinPos.x, MaxPos.x);
Y = Mathf.Clamp(Y, MinPos.y, MaxPos.y);
position = new Vector3(X, Y, position.z);
transform.position = position;
}
}