首页 > 解决方案 > Photon Pun 2 用鼠标改变位置

问题描述

我认为光子和鼠标位置之间存在问题。因为当我尝试使用键盘更改对象的位置时,它可以成功运行,但是当我尝试使用鼠标更改位置时,它并没有通过网络进行更改。如何在网络上通过鼠标位置更改对象位置?

public class SpehreControl : MonoBehaviour
{
    PhotonView PV;
    GameObject sphere1;
    GameObject bt;
    // Start is called before the first frame update
    void Start()
    {
        PV = GetComponent<PhotonView>();
        sphere1 = GameObject.Find("Sphere 1");
        bt = GameObject.Find("BT_1");
    }

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

            if (Input.GetMouseButton(0) && PV.IsMine)
            {
            PV.RPC("RPC_MoveOnline", RpcTarget.AllBuffered);
            }

    }



    [PunRPC]
    void RPC_MoveOnline()
    {
        transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
           Camera.main.ScreenToWorldPoint(Input.mousePosition).y, 0);

    }

}

标签: c#unity3dnetworkingmultiplayerphoton

解决方案


我认为是 RPC 函数的问题。当你调用它时,每个用户只会收到一个没有参数的调用事件。这意味着,每个用户都使用自己的 Input.mousePosition而不是来自发送者。

您可以使用参数来解决此问题:

...
   PV.RPC("RPC_MoveOnline", RpcTarget.AllBuffered, Camera.main.ScreenToWorldPoint(Input.mousePosition));
...
[PunRPC]
void RPC_MoveOnline(Vector3 worldPosition)
{
    transform.position = new Vector3(worldPosition.x, worldPosition.y, 0);
}

但这真的不是一个很好的方法......

如我所见,您需要为所有用户同步某些对象的位置。处理PhotonView组件(您的 GO 已经拥有的组件)要容易得多。只需将您的 GO Transform组件拖放到统一检查器中的PhotonView Observed Components 字段即可。

使用它,所有玩家的本地 GO 变换都会自动同步所有更改! 更多信息在这里

祝你好运!)


推荐阅读