版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Say__Yes/article/details/77782372
超简单的思路如下:既然摄像机要跟随物体,那就首先得有这个物体的位置信息。然后分别从位移和角度两个方面进行跟随。
第一,位移跟随:位移上首先得到物体的位置和摄像机的偏移,然后再使用Vector2.Lerp()插值实现。
第二,角度跟随:角度上需要使摄像机一直注视着主角(正对着主角),所以需要在主角和摄像机之间创建一个旋转角度,然后同样使用插值(不过这里是圆形插值Quaternion.Slerp( ))运算使摄像机注视着主角。
上代码(超简单):
using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour {
private Transform playerTrs;//主角位置
public float moveSpeed = 2;//射相机跟随的移动速度
// Use this for initialization
void Start () {
playerTrs = GameObject.FindGameObjectWithTag(Tags.player).transform;
}
// Update is called once per frame
void Update () {
//位移跟随
Vector3 targetPos = playerTrs.position + new Vector3(0f, 2.42f, -2.42f);
//Vector3(0f, 2.42f, -2.42f)这个向量是将摄像机放在需要跟随的物体下作为其子物体,然后把摄像机调到自己认为合适的位置所得到的向量坐标。
this.transform.position = Vector3.Lerp(this.transform.position, targetPos, moveSpeed * Time.deltaTime);
//角度跟随(使摄像机一直注视着主角)
//在主角和摄像机当前位置之间创建一个旋转角度,使用插值运算使摄像机注视主角
Quaternion targetRotation = Quaternion.LookRotation(playerTrs.position - this.transform.position);
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, targetRotation, moveSpeed * Time.deltaTime);
}
}