Unity多人游戏:当Y轴小于-2

时间:2018-06-14 11:31:50

标签: unity3d position unique multiplayer

当玩家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位置,如果小于-2,则将其重置为1。当你独自参加比赛时我就开始工作了,但是当你在比赛中超过1名球员时,它会做出奇怪的事情,因为它没有指向特定的球员。

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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,这将有助于保持玩家在所有动作中同步的位置。几乎所有网络游戏都必不可少的工具。