Unity中控制摄像机跟随人物主角的移动

首先进入场景中,把摄像机挂载到人物主角的下方,先作为主角的一个子物体存在,然后新建一个脚本CameraFllow,用于控制摄像机跟随,然后把这个脚本挂载摄像机上面,打开脚本,并复制以下的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFllow : MonoBehaviour {

    //摄像机
    private Transform m_Transform;
    //人物主角
    private Transform player_Transform;

    private Vector3 offset;

    void Start()
    {
        m_Transform = gameObject.GetComponent<Transform>();
        player_Transform = GameObject.Find("Necromancer").GetComponent<Transform>();
        //offset是摄像机相对于人物主角的相对位置
        offset = new Vector3(5.7f, 14.6f, -5.2f);
    }

    void Update()
    {
        //直接改变摄像机的位置(这种方式比较生硬,建议使用下一种插值的方式)
        //m_Transform.position = player_Transform.position + offset;

        //插值的方式控制摄像机的跟随
        m_Transform.position = Vector3.Lerp(m_Transform.position, player_Transform.position + offset, Time.deltaTime * 2);
    }

}

脚本中的offset就是摄像机相对于人物主角的局部座标,然后把自己场景中的摄像机局部座标复制给Vector3变量offset的x、y、z,操作完成保存脚本。
在这里插入图片描述

回到场景中,把摄像机脱离主角,作为世界座标系进行存在,不需要挂载到任何物体下面,不需要作为任何物体的子物体进行存在。
在这里插入图片描述

运行游戏,当主角进行移动的时候,摄像机也会跟随进行移动!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章