我正在使用UNET在Unity3D中构建Runnig Race多人游戏。我有2名球员直接在比赛地铁冲浪运动员。我想在运行谁是第一个和谁是第二个时更新播放器的位置,反之亦然,代码适用于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");
}
}
}
}
答案 0 :(得分:0)
所以这是我自己修复的答案。我做的是我添加了2个Slider for Player Position Indicator来显示谁是谁,谁是第二个,我将Slider的最小值设置为Player的Start Position和Max Value to Finish Position of the Player然后我比较了值滑块。
这是代码:
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;
}
}
}