【问题标题】:Sync Sprite renderer's flip with unet将 Sprite 渲染器的翻转与 unet 同步
【发布时间】:2018-02-12 18:08:13
【问题描述】:

我对 Unity 很陌生。我正在开发一个简单的多人游戏。

我面临的问题是当我们按下左右箭头键时,我无法同步精灵渲染器的翻转状态。

下面是我试过的代码。

[SerializeField] 
private SpriteRenderer spriteRenderer;

[Command]
void CmdProvideFlipStateToServer(bool state)
{
    spriteRenderer.flipX = state;
}

[ClientRpc]
void RpcSendFlipState(bool state)
{
    CmdProvideFlipStateToServer(state);
}

private void Flip()
{
    facingRight = !facingRight;
    if(isClient){
        spriteRenderer.flipX = !facingRight;
    }
    if(isLocalPlayer){
        RpcSendFlipState(spriteRenderer.flipX);
    }
}

【问题讨论】:

  • 从您的脚本中我无法真正看到您要归档的内容...?
  • 在按下左右箭头键时,我正在切换精灵渲染器 FlipX,我想同步这个切换

标签: unity3d unity3d-unet


【解决方案1】:

我假设你想要的是:

在任何时候都会在客户端上调用函数Flip()。

=> 他的本地 Sprite 已更改,您希望通过服务器将其同步到其他客户端。


如果是这种情况,您以错误的方式使用 Command 和 ClientRpc:

  • Command: 在客户端调用但只在服务端执行
  • ClientRpc:在服务器上调用,但只在(所有)客户端上执行

=> 你的脚本应该看起来像

[SerializeField] 
private SpriteRenderer spriteRenderer;

// invoked by clients but executed on the server only
[Command]
void CmdProvideFlipStateToServer(bool state)
{
    // make the change local on the server
    spriteRenderer.flipX = state;

    // forward the change also to all clients
    RpcSendFlipState(state)
}

// invoked by the server only but executed on ALL clients
[ClientRpc]
void RpcSendFlipState(bool state)
{
    // skip this function on the LocalPlayer 
    // because he is the one who originally invoked this
    if(isLocalPlayer) return;

    //make the change local on all clients
    spriteRenderer.flipX = state;
}

// Client makes sure this function is only executed on clients
// If called on the server it will throw an warning
// https://docs.unity3d.com/ScriptReference/Networking.ClientAttribute.html
[Client]
private void Flip()
{
    //Only go on for the LocalPlayer
    if(!isLocalPlayer) return;

    // make the change local on this client
    facingRight = !facingRight;
    spriteRenderer.flipX = !facingRight;

    // invoke the change on the Server as you already named the function
    CmdProvideFlipStateToServer(spriteRenderer.flipX);
}

【讨论】:

  • 谢谢你的回答,我会检查的。
猜你喜欢
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多