1

我正在使用 UNET 在 Unity3D 中构建 Runnig Race 多人游戏。我有 2 名玩家在游戏 Subway Surfer 中直接奔跑。我想在运行谁是第一谁是第二时更新玩家的位置,反之亦然,该代码适用于 Host Player,但不更新其他玩家的位置。请帮助我做错了什么。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class PlayerPosition : NetworkBehaviour {

    GameObject[] Players;
    Vector3 playerPos;


    void Start () {
        InvokeRepeating("UpdatePosition", 0.5f, 0.5f);
    }

    void UpdatePosition () {

        if (!isLocalPlayer)
            return;

            ClientPositionCalls();
    }

    [Client]
    void ClientPositionCalls()
    {
        CmdServerPosition();
    }

    [Command]
    public void CmdServerPosition()
    {
        Position();
    }

    [Server]
    public void Position()
    {
        playerPos = transform.position;
        RpcPosition(playerPos);
    }

    [ClientRpc]
    void RpcPosition(Vector3 pos)
    {
        if (isLocalPlayer)
        {
            playerPos = pos;
            Players = GameObject.FindGameObjectsWithTag("Player");
            foreach (GameObject p in Players)
            {

                if (p.transform.position.z < pos.z)
                    PlayerCanvas.canvas.WritePositionText("1");
                else
                    PlayerCanvas.canvas.WritePositionText("2");
            }
        }
    }
}
4

1 回答 1

0

所以这是我自己确定的答案。我所做的是我为玩家位置指示器添加了 2 个滑块以显示谁是第一和谁是第二,我将滑块的最小值设置为玩家的开始位置,将最大值设置为玩家的结束位置,然后我比较了值的滑块。

这是代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class PlayerPosition : NetworkBehaviour {

    GameObject[] Players;
    Vector3 playerPos;

    // Update is called once per frame
    void Update() {

        if (!isLocalPlayer)
            return;
            ClientPositionCalls();

            if (PlayerCanvas.canvas.hostDotObj.GetComponent<Slider>().value > PlayerCanvas.canvas.clientDotObj.GetComponent<Slider>().value)
            {
                PlayerCanvas.canvas.WritePositionText("1");
            } else
            {
                PlayerCanvas.canvas.WritePositionText("2");
            }
    }

    [Client]
    void ClientPositionCalls()
    {
        CmdServerPosition();
    }

    [Command]
    public void CmdServerPosition()
    {
        playerPos = transform.position;
        RpcPosition(playerPos);
    }

    [ClientRpc]
    void RpcPosition(Vector3 pos)
    {
        if (isLocalPlayer)
        {
            PlayerCanvas.canvas.hostDotObj.GetComponent<Slider>().value = transform.position.z;
            playerPos = pos;
        } else
        {
            PlayerCanvas.canvas.clientDotObj.GetComponent<Slider>().value = pos.z;
        }
    }
}
于 2018-03-30T05:02:39.787 回答