Unity多人游戏:当Y轴小于-2时重置玩家位置

问题描述 投票:0回答:2

当球员Y轴小于阈值-2时,我有重置球员位置的问题。

using UnityEngine;
using UnityEngine.Networking;

public class ResetPlayerPosition : NetworkManager {

    public float threshold = -2f;

    NetworkIdentity UniquePlayer;

    // On button click, it checks the players position and resets the position if values are true
    public void ResetPosition () {

        UniquePlayer = GameObject.Find("Player").GetComponent<NetworkIdentity>();
        var Player = GameObject.FindWithTag("Player");

        // Reset player position if the players Y axis is less than -2
        if (Player.transform.position.y < threshold) {
            Debug.Log("player position has been reset");
            Player.transform.position = new Vector3(0, 1, 0);
        } else {
            Debug.Log("Player position Y is currently at: " + Player.transform.position.y);
        }   
    }
}

我的目标是捕捉独特的球员y位置,并将其重置为1,如果它小于-2。当你独自参加比赛时,我得到了它的工作,但是一旦你在比赛中超过1名球员,它会做奇怪的事情,因为它没有指向特定的球员。

我正在使用NetworkManager并在localhost上运行它。我试图通过获取播放器的netID来解决这个问题,该网络ID是唯一的但无法弄清楚如何组合这些信息。

希望有人能指出我正确的方向。

unity3d position unique multiplayer
2个回答
0
投票

首先,我建议进行一些测试,以缩小主机系统和客户端系统上奇怪行为的差异。这可能会让我们深入了解到底出了什么问题。

其次,我同意塞巴斯蒂安的说法,将MonoBehaviour放在播放器预制件上可能是一个更好的方法。这样的事情应该是一个万无一失的解决方案:

using UnityEngine;

public class PositionReset : MonoBehaviour {
    public float threshold = -2;
    public float resetHeight = 1;

    private void Update() {
        if (transform.position.y < threshold) {
            // Note, I keep the x and z position the same, as it sounds like that's what you were looking for. Change as needed
            transform.position = new Vector3(transform.position.x, resetHeight, transform.position.z);
        }
    }
}

如果由于某种原因将行为放在播放器预制本身上是不可接受的,这里是您的代码段的修改版本,可能会解决此问题:

using UnityEngine;
using UnityEngine.Networking;

public class ResetPlayerPosition : NetworkManager {

    public float threshold = -2f;

    // On button click, it checks the players position and resets the position if values are true
    public void ResetPosition () {
        var Players = GameObject.FindGameObjectsWithTag("Player");

        foreach(GameObject Player in Players) {
            // Reset player position if the players Y axis is less than -2
            if (Player.transform.position.y < threshold) {
                Debug.Log("player position has been reset");
                Player.transform.position = new Vector3(0, 1, 0);
            } else {
                Debug.Log("Player position Y is currently at: " + Player.transform.position.y);
            }
        }
    }
}

您将注意到,我们不是使用播放器标记检索一个游戏对象,而是检索所有这些对象,并使用foreach循环对所有这些对象执行评估。这应该会产生更一致的行为。

除此之外,我会考虑使用NetworkTransform,这将有助于保持球员的位置在网络中同步进行所有动作;几乎所有网络游戏的必备工具。


1
投票

为什么不直接使用MonoBehaviour脚本并将其附加到播放器对象? 通过这个你已经有了正确的Player GameObject,你不必找到带有Tag的GameObject。

© www.soinside.com 2019 - 2024. All rights reserved.