unity 中简单的第三人称摄像机跟随原理

最简单的一种就是先设置好摄像机跟物体的相对距离,在脚本里就可以由物体的位置,跟相对距离,就可以求出摄像机的位置,用插值的方法可以让摄像机平滑跟随。
原理:摄像机与player以向量(有大小,有方向)相连,这样就可以确定摄像机与player的相对距离了,这样人物走动,摄像机也会跟随移动。


image.png

将下列代码与camera绑定就可以实现第三人称摄像机跟随。

public class CameraFollow : MonoBehaviour {

    // The position that that camera will be following.
    public Transform target; 
    // The speed with which the camera will be following.
    public float smoothing = 5f;        
    // The initial offset from the target.
    Vector3 offset;                      
    void Start() {
        // Calculate the initial offset.
        offset = transform.position - target.position;
    }

    void FixedUpdate () {
        // Create a postion the camera is aiming for based on the offset from the target.
        Vector3 targetCamPos = target.position + offset;
        
        // Smoothly interpolate between the camera's current position and it's target position.
        transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
    }
}

代码解释:
Transfrom

image.png

The Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform.
变换组件确定场景中每个对象的位置、旋转和比例。 每个游戏对象有一个转换。
Vector3
表示定义了一个三维向量
static function Lerp (from : Vector3, to : Vector3, t : float) : Vector3
image.png

关于vector3相关详细解释可查看链接http://www.ceeger.com/Script/Vector3/Vector3.html
image.png

FixedUpdate():固定更新事件,执行N次,0.02秒执行一次。所有物理组件相关的更新都在这个事件中处理。

将场景中的player(摄像机跟随的物体)拖入target中场景中的就可以实现简单的第三人称摄像机跟随。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容