初学Unity,学习到几种移动相机的方法,在这里记录一下,以后还会有补充。
简单移动:
给Main Camera挂载脚本:
public class MovieCamera : MonoBehaviour
{
//主相机的移动展现优雅的电影视角效果动画
public float speed = 10; //移动速度
private float endZ = -18.7f; //结束时的z坐标
private void Update()
{
if (transform.position.z < endZ) //尚未达到了目标点
{
//向前移动*时间间隔*速度
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
}
实现相机从当前位置移动到z坐标大于-18.7的位置。
Time.deltaTime:增量时间
即一秒内运行帧数的倒数。众所周知,update方法是每一帧运行一次,可是不同的环境下很有可能每一秒的帧数都会有出入,这就需要time.deltaTime这个量来做辅助。
例如:1秒是30帧(即Time.deltaTime为1/30),那就是会运行30次update方法,对应上面的代码,一秒下来的路程:
Vector3.forward*speed*30*1/30,也就实现了speed对应一秒钟的速度,也就方便了我们的控制
携程移动:
public void CameraMoveTo(Vector3 po, Vector3 qua)
{
StartCoroutine(CameraMove(po, qua));
}
IEnumerator CameraMove(Vector3 po, Vector3 qua)
{
yield return new WaitForSeconds(0.5f);
Vector3 TargetPosition = po;
Quaternion TargetRotation = Quaternion.Euler(qua);
while (MainCamera.transform.position != TargetPosition && Quaternion.Angle(MainCamera.transform.rotation, TargetRotation) >= 1)
{
//基于浮点数t返回a到b之间的插值,t限制在0~1之间。当t = 0返回from,当t = 1 返回to。当t = 0.5 返回from和to的平均值。
MainCamera.transform.position = new Vector3(Mathf.Lerp(MainCamera.transform.position.x, po.x + 0.1f, Time.deltaTime),
Mathf.Lerp(MainCamera.transform.position.y, po.y + 0.1f, Time.deltaTime),
Mathf.Lerp(MainCamera.transform.position.z, po.z + 0.1f, Time.deltaTime));
MainCamera.transform.rotation = Quaternion.Slerp(MainCamera.transform.rotation, TargetRotation, Time.deltaTime);
yield return 0;
}
}
商业转载 请联系作者获得授权,非商业转载 请标明出处,谢谢