【Unity2D】更好的相机跟随目标实现
实现效果:
1、相机跟随目标角色。
2、目标角色周围存在一个目标区域,角色在目标区域中移动相机不移动,角色离开目标区域边界时带动目标区域和相机一起移动。
3、相机跟随时平滑过渡。
将以下代码复制并挂载到相机上即可使用:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 相机跟随
/// </summary>
public class CameraFollow : MonoBehaviour
{
public void Start()
{
_focusArea = new FocusArea(_target.bounds, _focusSize);
_targetPos = transform.position;
}
public void Update()
{
if (_target == null) return;
_focusArea.Update(_target.bounds);
if(_focusArea.velocity != Vector2.zero)
{
_targetPos += (Vector3)_focusArea.velocity;
}
transform.position = Vector3.Lerp(transform.position, _targetPos, _smoothSpeed * Time.deltaTime);
}
private void OnDrawGizmos()
{
Gizmos.color = new Color(0.5f, 1, 0.5f, 0.5f);
Gizmos.DrawCube(_focusArea.center, _focusSize);
}
public Collider2D _target;
public Vector2 _focusSize;
public float _smoothSpeed = 20;
FocusArea _focusArea;
Vector3 _targetPos;
}
public class FocusArea
{
public FocusArea(Bounds focusBounds, Vector2 size)
{
left = focusBounds.center.x - size.x / 2;
right = focusBounds.center.x + size.x / 2;
top = focusBounds.min.y + size.y;
bottom = focusBounds.min.y;
center = new Vector2((left + right) / 2, (top + bottom) / 2);
velocity = Vector2.zero;
}
public void Update(Bounds targetBounds)
{
float shiftX = 0;
if (targetBounds.min.x < left)
{
shiftX = targetBounds.min.x - left;
}
else if (targetBounds.max.x > right)
{
shiftX = targetBounds.max.x - right;
}
left += shiftX;
right += shiftX;
float shiftY = 0;
if (targetBounds.max.y > top)
{
shiftY = targetBounds.max.y - top;
}
else if (targetBounds.min.y < bottom)
{
shiftY = targetBounds.min.y - bottom;
}
top += shiftY;
bottom += shiftY;
center = new Vector2((left + right) / 2, (top + bottom) / 2);
velocity = new Vector2(shiftX, shiftY);
}
public float left;
public float right;
public float top;
public float bottom;
public Vector2 center;
public Vector2 velocity;
}
本文作者:香菇0_0
本文链接:https://www.cnblogs.com/Xiang-gu/p/16894608.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步