1. 程式人生 > >Unity3D攝像機跟隨物體移動的程式碼控制

Unity3D攝像機跟隨物體移動的程式碼控制

攝像機跟隨物體方法一是把攝像機設定為物體Player的子物體,給Player新增移動腳步就可以攝像機跟隨Player移動。移動的簡單腳步

using UnityEngine;
using System.Collections;
//移動腳步
public class das : MonoBehaviour
{
    //設定速度,值可以改動試試
    private float speed = 10f;
    void Start()
    {

    }
    void Update()
    {
        //獲取unity自帶的移動W,A,S,D和上下左右鍵
        float h = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        float v = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        //移動物體,我現在是讓物體的X,Y的座標變化,transform.Translate(h, 0, v)是X,Z的座標變化,這個根據移動要求可修改
        transform.Translate(h, v, 0);
    }
}
這樣就可以實現簡單的攝像機跟隨物體了,可是根據我的個人使用情況,我是很少使用,因為我覺得總是有點卡的感覺,不推薦使用。接下來用一下方法二:程式碼控制攝像機跟隨物體。
</pre><pre name="code" class="csharp">using UnityEngine;
using System.Collections;
//指令碼掛在攝像機上
public class FollowPlayer : MonoBehaviour
{
    //定義一個Transform型別的player
    private Transform player;
    //定義攝像機與人物的偏移位置
    private Vector3 offsetStation;
    //在Awake裡獲取到移動物體Player的transform元件,其實也是初始化定義的欄位
    void Awake()
    {   
        //得到元件,先是給Player設定個Tag,當然也可以用Find來找Player名的方式,下面;但是不建議使用。
       // player = GameObject.Find("Player").transform;
        player = GameObject.FindGameObjectWithTag("Role").transform;
        //讓攝像機朝向人物的位置
        transform.LookAt(player.position);
        //得到偏移量
        offsetStation = transform.position - player.position;
    }
    void Update()
    {
        //讓攝像機的位置= 人物行走的位置+與偏移量的相加
        transform.position = offsetStation + player.position;

    }
}

這樣攝像機就可以跟隨物體Player移動了。