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射线检测也可以做到,而且更加简洁

posted @ 2022-03-31 10:46  三页菌  阅读(50)  评论(0编辑  收藏  举报