代码挂载到相机上
/* 使用与2D正交相机
* 平台跳跃类游戏
*/
using UnityEngine;
public class CameraFollowTarget : MonoBehaviour
{
Transform target; //看向的目标
public string lookTargetTag = "Player"; //看向目标的tag
public Vector2 tragetOffset = new Vector3(2, 2); //X轴和Y轴方向的偏移量
public float maxLimit; //右边界限制
public float minLimit; //左边界限制
private void Update()
{
if (target == null)
{
target = GameObject.FindGameObjectWithTag(lookTargetTag).transform;
return;
}
Follow();
}
private void Follow()
{
float xOffset = 0;
float yOffset = 0;
bool ismoveX = false;
bool ismoveY = false;
if (target.position.x < transform.position.x - tragetOffset.x)
{
xOffset = tragetOffset.x;
ismoveX = true;
}
else if (target.position.x > transform.position.x + tragetOffset.x)
{
xOffset = -tragetOffset.x;
ismoveX = true;
}
if (target.position .y < transform .position .y - tragetOffset.y)
{
yOffset = tragetOffset.y;
ismoveY = true;
}
else if(target.position.y > transform.position.y + tragetOffset.y)
{
yOffset = -tragetOffset.y;
ismoveY = true;
}
if (ismoveX)
{
float x = target.position.x + xOffset;
x = Mathf.Clamp(x,minLimit,maxLimit);
transform.position = new Vector3(x, transform .position .y, transform .position .z);
}
if (ismoveY)
{
transform.position = new Vector3(transform .position .x, target.position.y +yOffset , transform .position .z);
}
}
}