学习Unity的有趣时刻 1.镜头跟随

来源:互联网 发布:真正的男人 知乎 编辑:程序博客网 时间:2024/05/21 08:44

【1.关于视角跟随主角移动】 2017.11.29

学习来源是:https://www.cnblogs.com/kerrysx/p/4750010.html

using System.Collections;using System.Collections.Generic;using UnityEngine;public class CameraFollow : MonoBehaviour {public Transform target;//主角,也就是目标物体public float smothing = 5f;//镜头平滑移动的速度Vector3 offset;//摄像机和主角之间的固定距离void Start () {    target = GameObject.FindGameObjectWithTag ("Player").transform;    offset = transform.position - target.position;    //摄像机和主角之间的固定距离}void FixedUpdate () {    Vector3 targetCampos = target.position + offset;    transform.position = Vector3.Lerp(transform.position, targetCampos, smothing * Time.deltaTime);    //Vector3.Lerp的作用就是以一定的速度比例t,平滑的从start位置移动到end位置 }}

原理很简单,是一开始取镜头和主角的位置并通过相减得到固定的距离,然后镜头一直保持这个固定的距离,这样就可以实现镜头跟随。

关于Vector3.Lerp线性插值的详细参考:
http://blog.csdn.net/qq_26999509/article/details/53608119

线性插值的几何意义即为概述图中利用过A点和B点的直线来近似表示原函数。线性插值可以用来近似代替原函数,也可以用来计算得到查表过程中表中没有的数值。(源自百度百科)

上面的这种方法只能简单实现了镜头跟随,但没有实现无论怎么旋转物体,摄像机视角也一直跟在物体后面,也就是一般第三人称游戏的那种效果。

2017.12.4更新
关于视角也跟随物体转动而改变,这篇帖子给了我启发:
https://tieba.baidu.com/p/3447777824

原内容就不贴了,贴一下自己修改过的代码以及个人对代码的理解

using UnityEngine;using System.Collections;public class CameraControl : MonoBehaviour {public Animator animator;public GameObject sight;  //相机注视的目标public float velocity = 0.5f;  //相机平滑运动的速度private Vector3 offset;   //物体与摄像机之间的距离private float currentAngleX;private float currentAngleY;  //这两个变量都是当前要让相机转动到哪个角度Quaternion rotation = Quaternion.Euler (0, 0, 0);void Start () {    offset = sight.transform.position - transform.position;    currentAngleX = 0;    currentAngleY = 0;    }void LateUpdate () {    AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);    //物体绕某个轴旋转的角度,后面是.x就是绕x轴,后面是.y就是绕y轴    float desireAngleX = sight.transform.eulerAngles.y;    float desireAngleY = sight.transform.eulerAngles.x;    //0.5的作用是计算currentAngle和desireAngle的中间值,然后把这个值作为新的当前角度,如此便能实现平滑跟踪。    currentAngleX = Mathf.LerpAngle (currentAngleX, desireAngleX, velocity);    currentAngleY = Mathf.LerpAngle (currentAngleY, desireAngleY, velocity);    transform.position = sight.transform.position - (rotation * offset);    transform.LookAt (sight.transform);    }}

关于平滑追踪,原文给出的解释是:
到现在为止我们所写的跟踪都是角色转动时,向量【立刻】跟着转动。显然,所谓平滑跟踪就是降低跟踪的速度,也就是滞后一段时间才到达“我们期望的角度”desireAngle。

原文所说的摄像机抖动尚未体会到,大概以后代码复杂了会有?
那我还是先存着这个摄像机抖动的分析吧:
http://blog.csdn.net/yxriyin/article/details/39237673

原创粉丝点击