1. 程式人生 > 其它 >Unity 三行程式碼實現 玩家跟隨移動平臺移動,非設定父節點

Unity 三行程式碼實現 玩家跟隨移動平臺移動,非設定父節點

非設定父節點,核心程式碼只需要3行

using System.Collections.Generic;
using UnityEngine;

public class Platform : MonoBehaviour
{
    List<Player> players = new List<Player>();
    public int num;
    private Vector3 offset = Vector3.zero;
    private int index;
    private Vector3 originPos;
    
    void
FixedUpdate() { for (int i = players.Count - 1; i >= 0; i--) { Player player = players[i]; Vector3 pos = transform.position; /*------------------------------核心程式碼--------------------------------------*/ //計算平臺的位移差 offset = pos - originPos;
//設定玩家位置 player.transform.position += offset; //重置originPos originPos = pos; /*--------------------------------------------------------------------------*/ } num = players.Count; } private void OnTriggerStay(Collider other) { AddPlayer(other); originPos
= transform.position; } private void OnTriggerEnter(Collider other) { AddPlayer(other); //當玩家接觸平臺時,記錄平臺的位置 originPos = transform.position; } private void OnTriggerExit(Collider other) { RemovePlayer(other); } private void RemovePlayer(Collider other) { Player player = other.GetComponent<Player>(); if (null != player) { if (players.Contains(player)) { players.Remove(player); } } } private void AddPlayer(Collider other) { Player player = other.GetComponent<Player>(); if (null != player) { if (!players.Contains(player)) { players.Add(player); } } } }

 

這個是使用Collider的方式,使用Box射線檢測也可以做到,而且更加簡潔