Unity NetworkTransform:同步两个玩家

时间:2016-03-09 12:39:48

标签: c# unity3d client-server multiplayer

我正在努力开发一个在线乒乓球。我正在使用masterserver。 我希望我的游戏能够同步服务器上的两个玩家,所以我检查:  当是本地播放器时,它在服务器上同步移动;  当其他玩家在服务器上同步时,它应该在其他客户端显示移动。

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

public class Movement : NetworkBehaviour {

  private Vector2 speedx = new Vector2(3,0);
  private float lastSynchronizationTime = 0f;
  private float syncDelay = 0f;
  private float syncTime = 0f;
  private Vector2 syncStartPosition = Vector2.zero;
  private Vector2 syncEndPosition = Vector2.zero;

  // Update is called once per frame
  void Update()
  {
     if (isLocalPlayer)
     {
         InputMovement();
     }
    else
     {
         SyncedMovement();
     }
  }

  private void SyncedMovement()
  {
    syncTime += Time.deltaTime;
    GetComponent<Rigidbody2D>().position = Vector2.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
  }

  void InputMovement()
  {

    if (Input.GetKey(KeyCode.D))
        GetComponent<Rigidbody2D>().MovePosition(GetComponent<Rigidbody2D>().position + speedx * Time.deltaTime);
    if (Input.GetKey(KeyCode.A))
        GetComponent<Rigidbody2D>().MovePosition(GetComponent<Rigidbody2D>().position - speedx * Time.deltaTime);
  }

  void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
  {
    Vector3 syncPosition = Vector3.zero;
    Vector3 syncVelocity = Vector3.zero;
    if (stream.isWriting)
    {
        syncPosition = GetComponent<Rigidbody2D>().position;
        stream.Serialize(ref syncPosition);
        syncVelocity = GetComponent<Rigidbody2D>().velocity;
        stream.Serialize(ref syncVelocity);
    }
    else
    {
        stream.Serialize(ref syncPosition);
        stream.Serialize(ref syncVelocity);

        syncTime = 0f;
        syncDelay = Time.time - lastSynchronizationTime;
        lastSynchronizationTime = Time.time;

        syncEndPosition = syncPosition + syncVelocity * syncDelay;
        syncStartPosition = GetComponent<Rigidbody>().position;
        Debug.Log("syncstart");
    }
  }
}

有人可以帮我同步两名球员吗? 编辑: 当我启动服务器时,服务器的播放器产生,但我无法移动它。 当我启动客户端时,客户端的播放器在服务器上生成,但服务器的播放器不在客户端窗口中显示。我无法移动客户端和服务器。

0 个答案:

没有答案