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

  • 相关阅读:
    Java实现批量下载《神秘的程序员》漫画
    mysql远程连接:ERROR 1130 (HY000): Host '*.*.*.*' is not allowed to connect to this MySQL server解决办法
    opencv学习_15 (利用cmake查看opencv的源码)
    jobs 命令
    中断子系统6_中断嵌套处理
    JPA一对多映射
    JPA Map映射
    JPA集合映射
    JPA删除实体
    JPA查找实体
  • 原文地址:https://www.cnblogs.com/sanyejun/p/16080699.html
Copyright © 2020-2023  润新知