【问题标题】:Photon 2d game multiplayer lagsPhoton 2d 多人游戏延迟
【发布时间】:2014-07-24 04:38:55
【问题描述】:

我有一个使用 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();
        }

    }
}

【问题讨论】:

    标签: unity3d 2d multiplayer photon


    【解决方案1】:

    来自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);
    

    【讨论】:

    • 我对 Photon 不熟悉,但我认为增加 lastUpdateTime 应该会使它看起来更平滑。尽管改用 this tutorial 的插值部分中的代码可能会更好,因为它应该能更好地应对慢速网络。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    相关资源
    最近更新 更多