在游戏场景中,主角在场景中移动需要摄像机跟随主角移动,本文主要介绍简单的主角移动。
PlayerMove:
public class PlayerMove : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x=Input.GetAxis("Horizontal");//获取水平方向偏移
float z=Input.GetAxis("Vertical");//获取垂直方向偏移量
if(x!=0||z!=0)
{
this.transform.LookAt(this.transform.position+new Vector3(x,0,z));//转向前方
this.transform.Translate(transform.forward*Time.deltaTime*3,Space.World);//移动
}
}
}
相机跟随,CameraFollow:
public class CameraFollow : MonoBehaviour
{
public Transform target;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset=target.transform.position-this.transform.position;//设置目标对象与相机之间的差值
}
// Update is called once per frame
void Update()
{
this.transform.position=target.transform.position-offset;//相机跟随
}
}
在初始化时,根据相机和角色之间的距离设置相机跟随的差值。