Skip to content

[Unity] 讓其他物件跟隨著玩家移動

在 Unity 中若要製作出跟隨玩家移動的物件,比方說寵物或棺材(?),那麼我們可以使用 List<Vector3> 資料型態的變數將玩家的移動路線(也就是每個時間點存在的位置)記錄起來,並讓想要跟隨玩家的物件位置不斷地更新。


範例

為了示範,我在場景中新增了兩個物件: player 以及 pet。為了做出區別,我分別給予了不同顏色。


接著,在玩家身上附加 playerMove.cs 的腳本。

using System.Collections.Generic;
using UnityEngine;

public class playerMove : MonoBehaviour
{
    public GameObject petObject;
    public List<Vector3> positionList;
    public int distance = 20;
    public float speed = 0.1f;

    void FixedUpdate()
    {
        // Move
        if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += new Vector3(0, speed, 0);
        }

        if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.position += new Vector3(0, -speed, 0);
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position += new Vector3(-speed, 0, 0);
        }

        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += new Vector3(speed, 0, 0);
        }

        // Pet following
        positionList.Add(transform.position);

        if (positionList.Count > distance)
        {
            positionList.RemoveAt(0);
            petObject.transform.position = positionList[0];
        }
    }
}




別忘了,要在 Unity 編輯器中將 pet 的物件在 Inspector 中附加給 player 物件的腳本。


最後,我錄段影片來看看這個物件跟隨腳本的效果。


References


Read More

Tags:

Leave a Reply