Photon 2d游戏多人游戏滞后

时间:2014-06-03 18:06:29

标签: unity3d 2d multiplayer photon

我有一个使用Photon的2D多人游戏,其中所有的动作都是由RigidBody 2d制作的。当两个玩家都连接起来时,我可以看到我的对手动作,但是他们并不顺畅。 上次更新时间变量设置为0.25。

using UnityEngine;
using System.Collections;

public class NetworkCharacter : Photon.MonoBehaviour {

    Vector3 realPosition = Vector3.zero;
    Quaternion realRotation = Quaternion.identity;
    public float lastUpdateTime = 0.1f;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void FixedUpdate () {
         if(photonView.isMine){
            //Do nothing -- we are moving
        }
        else {
            transform.position = Vector3.Lerp(transform.position, realPosition, lastUpdateTime);
            transform.rotation = Quaternion.Lerp(transform.rotation, realRotation, lastUpdateTime);
        }
    }

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info){
        if(stream.isWriting){
            //This is OUR player.We need to send our actual position to the network
            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation); 
    }else{
            //This is someone else's player.We need to receive their positin (as of a few millisecond ago, and update our version of that player.
            realPosition = (Vector3)stream.ReceiveNext();
            realRotation = (Quaternion)stream.ReceiveNext();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

来自unity script reference

[Lerp] Interpolates between from and to by the fraction t. This is most commonly used to find a point some fraction of the way along a line between two endpoints (eg, to move an object gradually between those points). This fraction is clamped to the range [0...1]. When t = 0 returns from. When t = 1 returns to. When t = 0.5 returns the point midway between from and to.

所以基本上Vector3.Lerp会返回:

from + ((to - from) * t)

正如您所看到的,通过使用相同的值调用Lerp,它始终返回相同的值,您应使用的是MoveTowardsRotateTowards

transform.position = Vector3.MoveTowards(transform.position, realPosition, lastUpdateTime * Time.deltaTime);
transform.rotation = Quaternion.RotateTowards(transform.rotation, realRotation, lastUpdateTime * Time.deltaTime);