实现思路
我们给相机对象添加脚本后,在脚本中获取主角的位置信息,将主角的位置信息与相机的位置信息做对比,如果主角和相机的位置相差过大,则改变相机位置坐标。 ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 这个脚本用来控制摄像机跟随角色移动
public class FellowPlayer : MonoBehaviour
{
public GameObject player;
public float speed = 50;
//public float minPosX;
//public float maxPosY;
// Start is called before the first frame update
void Start()
{
string tag = "Player";
player = GameObject.FindGameObjectWithTag(tag);
//Debug.Log("获取对象");
}
// Update is called once per frame
void Update()
{
//FixCameraPos();
}
void FixedUpdate()
{
FixCameraPos();
}
void FixCameraPos()
{
float pPosX = player.transform.position.x; //主角 x轴方向 时实坐标值
float cPosX = transform.position.x; //相机 x轴方向 时实坐标值
float pPosY = player.transform.position.y;
float cPosY = transform.position.y;
//Debug.Log("主角坐标x=" + pPosX.ToString());
// 当角色和相机之间的像素差大于这个值的时候才移动相机
float value = 1;
// 记录相机的新的坐标值
float newPosX = transform.position.x;
float newPosY = transform.position.y;
if(pPosX - cPosX > value)
{
newPosX = cPosX + speed * Time.deltaTime;
newPosY = cPosY;
}
else if (pPosX - cPosX < -value)
{
newPosX = cPosX - speed * Time.deltaTime;
newPosY = cPosY;
}
else if (pPosY - cPosY > value)
{
newPosX = cPosX;
newPosY = cPosY + speed * Time.deltaTime;
}
else if (pPosY - cPosY < -value)
{
newPosX = cPosX;
newPosY = cPosY - speed * Time.deltaTime;
}
transform.position = new Vector3(newPosX, newPosY, transform.position.z);
}
};
|