【发布时间】:2015-03-16 07:50:44
【问题描述】:
我有 2 个脚本:
- 网络管理器
- PlayerScript
和游戏对象播放器: 对于控制网络,我有 GameObject 脚本: PlayerScript 代码:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public float speed = 10f;
private float lastSynchronizationTime = 0f;
private float syncDelay = 0f;
private float syncTime = 0f;
private Vector3 syncStartPosition = Vector3.zero;
private Vector3 syncEndPosition = Vector3.zero;
private void InputMovement()
{
if (Input.GetKey(KeyCode.W))
rigidbody2D.MovePosition(rigidbody2D.position + Vector2.up * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.S))
rigidbody2D.MovePosition(rigidbody2D.position - Vector2.up * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.D))
rigidbody2D.MovePosition(rigidbody2D.position + Vector2.right * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.A))
rigidbody2D.MovePosition(rigidbody2D.position - Vector2.right * speed * Time.deltaTime);
}
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
Debug.Log("OnSerializeNetworkView!!!!!!!!!!!!!!!!!!!!");
Vector3 syncPosition = Vector3.zero;
Vector3 syncVelocity = Vector3.zero;
if (stream.isWriting)
{
syncPosition = rigidbody2D.position;
stream.Serialize(ref syncPosition);
syncPosition = 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 = rigidbody2D.position;
}
}
void Awake()
{
lastSynchronizationTime = Time.time;
}
void Update()
{
if (networkView.isMine)
{
InputMovement();
}
else
{
SyncedMovement();
}
}
[RPC]
private void SyncedMovement()
{
syncTime += Time.deltaTime;
rigidbody2D.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
Debug.Log(syncStartPosition+ " ####### " +rigidbody2D.position+ " ####### " +syncEndPosition);
}
}
和 NetworkManager 代码:
using UnityEngine;
using System.Collections;
public class NetworkManager : MonoBehaviour {
public Transform point1;
public Transform point2;
public GameObject player;
// Use this for initialization
void Start () {
if (Network.isServer) {
Network.Instantiate(player,point1.transform.position,Quaternion.identity,0);
}
}
void OnPlayerConnected ( NetworkPlayer netPlayer)
{
Debug.Log("Player " + " connected from " + netPlayer.ipAddress + ":" + netPlayer.port);
networkView.RPC("net_DoSpawn",RPCMode.All);
}
[RPC]
void net_DoSpawn()
{
Network.Instantiate(player,point2.transform.position,Quaternion.identity,0);
}
}
我多次尝试调试id,但没有改变。 OnSerializeNetworkView 没有被调用并且玩家被生成了两次。如果我试图去其他玩家的位置,他们开始闪烁,否则他们不可见。任何人都可以帮助我吗?非常感谢和抱歉我的英语:))
【问题讨论】:
-
如果您要在问题中转储一堆屏幕截图和那么多代码,我建议您在顶部介绍您的问题和问题。这样,人们在滚动代码时就知道他们实际在寻找什么(如果可以的话,确实应该减少)。
标签: c# networking unity3d 2d rpc