Vector3.Lerp помогите разобраться.

Vector3.Lerp помогите разобраться.

Сообщение Dantalian 07 авг 2013, 17:38

здравствуйте, уважаемые форумчане! Очень прошу помочь решить одну проблему, т.к. найти решения сам я не смог. Искал в других местах, с тем же результатом, так что вы моя последняя надежда :) . Проблема вот в чем: не получается корректное сглаживание, все промежуточные кадры, созданные этой опцией всегда создаются на (0,0,0) координатах. Перерыл кучу примеров в интернете, в т. ч на англоязычных сайтах,но не смог найти хотябы простейший пример, как это работает. Если есть добрый человек, желающий помочь, буду жутко рад=). P.S. Прилагаю скрипт.
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class Control : Photon.MonoBehaviour {
       
  public GameObject Player;
  public Vector3 vec3 = Vector3.zero;
  private float speed = 0f;
  public float tm = 1.0f;
       
void Start ()
  {
  Player = (GameObject)this.gameObject;
  }

void Update()
        {
         if (!photonView.isMine)
         {
         transform.position = Vector3.Lerp(transform.position, vec3, Time.deltaTime * 5);
     }
    Move();
        }
void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.isWriting)
        {
            stream.SendNext(transform.position);
        }
        else
        {
            vec3 = (Vector3)stream.ReceiveNext();
                }
        }
void Move()
  {

   {   
    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.LeftArrow))
   {
    vec3 = new Vector3(Player.transform.position.x ,Player.transform.position.y, Player.transform.position.z+speed);
        tm -= 60.0f*Time.deltaTime;
        Debug.Log(tm);
       
    }
        phe();
        tre();
        stop1();
  }
}
void tre()
                {
                if (tm <= 0)
                {
                transform.position = vec3;
                tm = 1;
                }              
        }
void phe()
            {
                if (speed <= 1.5f)
                {
                speed = speed +0.002f;
        }              
        }      
void stop1()
        {
                if (Input.GetKeyUp(KeyCode.W))
                {
                speed = 0f;

        }              
    }
}

Спасибо за внимание. :)
Dantalian
UNец
 
Сообщения: 9
Зарегистрирован: 20 ноя 2012, 13:53

Re: Vector3.Lerp помогите разобраться.

Сообщение ximael 07 авг 2013, 19:54

Код не имеет смысла.
Есть юнитивский пример сглаживания, почему бы от него не отталкиваться?
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class NetworkInterpolatedTransform : MonoBehaviour {
       
        public double interpolationBackTime = 0.1;
       
        internal struct  State
        {
                internal double timestamp;
                internal Vector3 pos;
                internal Quaternion rot;
        }

        // We store twenty states with "playback" information
        State[] m_BufferedState = new State[20];
        // Keep track of what slots are used
        int m_TimestampCount;
       
        void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
        {
                // Always send transform (depending on reliability of the network view)
                if (stream.isWriting)
                {
                        Vector3 pos = transform.localPosition;
                        Quaternion rot = transform.localRotation;
                        stream.Serialize(ref pos);
                        stream.Serialize(ref rot);
                }
                // When receiving, buffer the information
                else
                {
                        // Receive latest state information
                        Vector3 pos = Vector3.zero;
                        Quaternion rot = Quaternion.identity;
                        stream.Serialize(ref pos);
                        stream.Serialize(ref rot);
                       
                        // Shift buffer contents, oldest data erased, 18 becomes 19, ... , 0 becomes 1
                        for (int i=m_BufferedState.Length-1;i>=1;i--)
                        {
                                m_BufferedState[i] = m_BufferedState[i-1];
                        }
                       
                        // Save currect received state as 0 in the buffer, safe to overwrite after shifting
                        State state;
                        state.timestamp = info.timestamp;
                        state.pos = pos;
                        state.rot = rot;
                        m_BufferedState[0] = state;
                       
                        // Increment state count but never exceed buffer size
                        m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);

                        // Check integrity, lowest numbered state in the buffer is newest and so on
                        for (int i=0;i<m_TimestampCount-1;i++)
                        {
                                if (m_BufferedState[i].timestamp < m_BufferedState[i+1].timestamp)
                                        Debug.Log("State inconsistent");
                        }
                       
                        //Debug.Log("stamp: " + info.timestamp + "my time: " + Network.time + "delta: " + (Network.time - info.timestamp));
                }
        }
       
        // This only runs where the component is enabled, which is only on remote peers (server/clients)
        void Update () {
                double currentTime = Network.time;
                double interpolationTime = currentTime - interpolationBackTime;
                // We have a window of interpolationBackTime where we basically play
                // By having interpolationBackTime the average ping, you will usually use interpolation.
                // And only if no more data arrives we will use extrapolation
               
                // Use interpolation
                // Check if latest state exceeds interpolation time, if this is the case then
                // it is too old and extrapolation should be used
                if (m_BufferedState[0].timestamp > interpolationTime)
                {
                        for (int i=0;i<m_TimestampCount;i++)
                        {
                                // Find the state which matches the interpolation time (time+0.1) or use last state
                                if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount-1)
                                {
                                        // The state one slot newer (<100ms) than the best playback state
                                        State rhs = m_BufferedState[Mathf.Max(i-1, 0)];
                                        // The best playback state (closest to 100 ms old (default time))
                                        State lhs = m_BufferedState[i];
                                       
                                        // Use the time between the two slots to determine if interpolation is necessary
                                        double length = rhs.timestamp - lhs.timestamp;
                                        float t = 0.0F;
                                        // As the time difference gets closer to 100 ms t gets closer to 1 in
                                        // which case rhs is only used
                                        if (length > 0.0001)
                                                t = (float)((interpolationTime - lhs.timestamp) / length);
                                       
                                        // if t=0 => lhs is used directly
                                        transform.localPosition = Vector3.Lerp(lhs.pos, rhs.pos, t);
                                        transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
                                        return;
                                }
                        }
                }
                // Use extrapolation. Here we do something really simple and just repeat the last
                // received state. You can do clever stuff with predicting what should happen.
                else
                {
                        State latest = m_BufferedState[0];
                       
                        transform.localPosition = latest.pos;
                        transform.localRotation = latest.rot;
                }
        }
}
 
Музыка и звуковой дизайн для игр
Bomb Heroes - Бомбермен онлайн
ximael
UNец
 
Сообщения: 36
Зарегистрирован: 20 апр 2013, 00:23

Re: Vector3.Lerp помогите разобраться.

Сообщение Dantalian 07 авг 2013, 20:27

ximael писал(а):Код не имеет смысла.

Именно это я и хочу понять, почему код не имеет смысла, а так же, что в нем не так.
ximael писал(а):Есть юнитивский пример сглаживания, почему бы от него не отталкиваться?

Без понимания что я делаю не так я не смогу адаптировать этот код правильно.
Dantalian
UNец
 
Сообщения: 9
Зарегистрирован: 20 ноя 2012, 13:53

Re: Vector3.Lerp помогите разобраться.

Сообщение ximael 07 авг 2013, 22:03

https://developer.valvesoftware.com/wik ... working:ru
Задача стоит получать с сервера координаты, запихивать их в буфер с меткой времени и, по мере надобности, доставать из буфера необходимые 2 точки, между которыми делается интерполяция.
Vector3.Lerp(v1, v2, t) - не волшебная функция, в мануал.
Time.deltaTime - время между кадрами.
Грубо говоря, обновления приходят 2 раза в секунду, есть 3 позиции, например, секунду назад v2, полсекунды назад v1 и сейчас v0. Добавим лаг в секунду. Как только приходит новая координата, v2=v1, v1=v0, v0=новая координата, t=0;
Update(){
Отображаемая позиция объекта = Vector3.Lerp(v1, v0, t);
\\t должна быть от 0 до 1
t+=Time.deltaTime*2;\\2, т.к. обновление 2 раза в секунду
}
Музыка и звуковой дизайн для игр
Bomb Heroes - Бомбермен онлайн
ximael
UNец
 
Сообщения: 36
Зарегистрирован: 20 апр 2013, 00:23

Re: Vector3.Lerp помогите разобраться.

Сообщение Dantalian 08 авг 2013, 12:06

Спасибо, стало ясней. Вопрос возник, с Cloud это можно использовать? Или есть еще какие-то особенности?
Dantalian
UNец
 
Сообщения: 9
Зарегистрирован: 20 ноя 2012, 13:53

Re: Vector3.Lerp помогите разобраться.

Сообщение ximael 08 авг 2013, 12:50

Музыка и звуковой дизайн для игр
Bomb Heroes - Бомбермен онлайн
ximael
UNец
 
Сообщения: 36
Зарегистрирован: 20 апр 2013, 00:23

Re: Vector3.Lerp помогите разобраться.

Сообщение Dantalian 08 авг 2013, 14:00

Я пробую раз за разом, но проблема не меняется. Все время кадры сглаживаются на (0,0,0). Вытащив скрипт из демо Викингов эффект тот же, хотя там он работал. Можно более точно определить, в чем именно проблема? :(
Dantalian
UNец
 
Сообщения: 9
Зарегистрирован: 20 ноя 2012, 13:53

Re: Vector3.Lerp помогите разобраться.

Сообщение ximael 08 авг 2013, 15:04

Сделай отдельно скрипт с управлением перса в Update, через transform.Translate, с умножением скорости на time.deltaTime. Не надо менять значение скорости, надо:
Синтаксис:
Используется csharp
void Update()
if(нажата W)transform.translate(направление движения*скорость*time.deltatime);
также для других
}
 

Проверь в сингле.
Приаттачь скрипт юнитивский с изменением monobehaviour на фотоновский и методов или из викингов(не знаю как работает, не видел).
Выложи, что наваяешь.
Музыка и звуковой дизайн для игр
Bomb Heroes - Бомбермен онлайн
ximael
UNец
 
Сообщения: 36
Зарегистрирован: 20 апр 2013, 00:23

Re: Vector3.Lerp помогите разобраться.

Сообщение Dantalian 08 авг 2013, 17:37

Вот управление.
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class Control : MonoBehaviour {
       
  public GameObject Player;
  private float speed = 15f;
       
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
    transform.Translate(Vector3.forward * speed * Time.deltaTime);
       
        if (Input.GetKey(KeyCode.S))
        transform.Translate(Vector3.forward * -speed * Time.deltaTime);
       
        if (Input.GetKey(KeyCode.D))
        transform.Translate(Vector3.right * speed * Time.deltaTime);
                               
        if (Input.GetKey(KeyCode.A))
        transform.Translate(Vector3.right * -speed * Time.deltaTime);
        }
  }
 


При этом скрипте объекты не движутся.

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class ThirdPersonNetworkVik : Photon.MonoBehaviour
{
    ThirdPersonCameraNET cameraScript;
    ThirdPersonControllerNET controllerScript;

    void Awake()
    {
        cameraScript = GetComponent<ThirdPersonCameraNET>();
        controllerScript = GetComponent<ThirdPersonControllerNET>();

    }
    void Start()
    {
        //TODO: Bugfix to allow .isMine and .owner from AWAKE!
        if (photonView.isMine)
        {
            //MINE: local player, simply enable the local scripts
            cameraScript.enabled = true;
            controllerScript.enabled = true;
            Camera.main.transform.parent = transform;
            Camera.main.transform.localPosition = new Vector3(0, 2, -10);
            Camera.main.transform.localEulerAngles = new Vector3(10, 0, 0);

        }
        else
        {          
            cameraScript.enabled = false;
            controllerScript.enabled = true;

        }
        controllerScript.SetIsRemotePlayer(!photonView.isMine);

        gameObject.name = gameObject.name + photonView.viewID;
    }

    void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.isWriting)
        {
            //We own this player: send the others our data
           // stream.SendNext((int)controllerScript._characterState);
            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation);
            stream.SendNext(rigidbody.velocity);

        }
        else
        {
            //Network player, receive data
            //controllerScript._characterState = (CharacterState)(int)stream.ReceiveNext();
            correctPlayerPos = (Vector3)stream.ReceiveNext();
            correctPlayerRot = (Quaternion)stream.ReceiveNext();
            rigidbody.velocity = (Vector3)stream.ReceiveNext();
        }
    }

    private Vector3 correctPlayerPos = Vector3.zero; //We lerp towards this
    private Quaternion correctPlayerRot = Quaternion.identity; //We lerp towards this

    void Update()
    {
        if (!photonView.isMine)
        {
            //Update remote player (smooth this, this looks good, at the cost of some accuracy)
            transform.position = Vector3.Lerp(transform.position, correctPlayerPos, Time.deltaTime * 5);
            transform.rotation = Quaternion.Lerp(transform.rotation, correctPlayerRot, Time.deltaTime * 5);
        }
    }

    void OnPhotonInstantiate(PhotonMessageInfo info)
    {
        //We know there should be instantiation data..get our bools from this PhotonView!
        object[] objs = photonView.instantiationData; //The instantiate data..
        bool[] mybools = (bool[])objs[0];   //Our bools!

        //disable the axe and shield meshrenderers based on the instantiate data
        MeshRenderer[] rens = GetComponentsInChildren<MeshRenderer>();
        rens[0].enabled = mybools[0];//Axe
        rens[1].enabled = mybools[1];//Shield

    }

}


Этот из викингов при нем кадры уходят к (0,0,0) + второй игрок немного дергается при движении.

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class ThirdPersonNetworkVik : Photon.MonoBehaviour
{
    ThirdPersonCameraNET cameraScript;
    ThirdPersonControllerNET controllerScript;

    void Awake()
    {
        cameraScript = GetComponent<ThirdPersonCameraNET>();
        controllerScript = GetComponent<ThirdPersonControllerNET>();

    }
    void Start()
    {
        //TODO: Bugfix to allow .isMine and .owner from AWAKE!
        if (photonView.isMine)
        {
            //MINE: local player, simply enable the local scripts
            cameraScript.enabled = true;
            controllerScript.enabled = true;
            Camera.main.transform.parent = transform;
            Camera.main.transform.localPosition = new Vector3(0, 2, -10);
            Camera.main.transform.localEulerAngles = new Vector3(10, 0, 0);

        }
        else
        {          
            cameraScript.enabled = false;
            controllerScript.enabled = true;

        }
        controllerScript.SetIsRemotePlayer(!photonView.isMine);

        gameObject.name = gameObject.name + photonView.viewID;
    }

    void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.isWriting)
        {
            //We own this player: send the others our data
           // stream.SendNext((int)controllerScript._characterState);
            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation);
            stream.SendNext(rigidbody.velocity);

        }
        else
        {
            //Network player, receive data
            //controllerScript._characterState = (CharacterState)(int)stream.ReceiveNext();
            correctPlayerPos = (Vector3)stream.ReceiveNext();
            correctPlayerRot = (Quaternion)stream.ReceiveNext();
            rigidbody.velocity = (Vector3)stream.ReceiveNext();
        }
    }

    private Vector3 correctPlayerPos = Vector3.zero; //We lerp towards this
    private Quaternion correctPlayerRot = Quaternion.identity; //We lerp towards this

    void Update()
    {
        if (!photonView.isMine)
        {
            //Update remote player (smooth this, this looks good, at the cost of some accuracy)
            transform.position = Vector3.Lerp(transform.position, correctPlayerPos, Time.deltaTime * 5);
            transform.rotation = Quaternion.Lerp(transform.rotation, correctPlayerRot, Time.deltaTime * 5);
        }
    }

    void OnPhotonInstantiate(PhotonMessageInfo info)
    {
        //We know there should be instantiation data..get our bools from this PhotonView!
        object[] objs = photonView.instantiationData; //The instantiate data..
        bool[] mybools = (bool[])objs[0];   //Our bools!

        //disable the axe and shield meshrenderers based on the instantiate data
        MeshRenderer[] rens = GetComponentsInChildren<MeshRenderer>();
        rens[0].enabled = mybools[0];//Axe
        rens[1].enabled = mybools[1];//Shield

    }

}


Пробовал и другие тот же результат.
Dantalian
UNец
 
Сообщения: 9
Зарегистрирован: 20 ноя 2012, 13:53

Re: Vector3.Lerp помогите разобраться.

Сообщение ximael 08 авг 2013, 18:54

При этом скрипте объекты не движутся.

Как не движутся? В одиночном режиме должны двигаться.

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class ThirdPersonNetwork : Photon.MonoBehaviour
{
     Control control;//скрипт, где управление

     void Awake()
     {
         control = GetComponent<Control>();
     }
     void Start()
     {
         if (!photonView.isMine)//если чужой персонаж, на нажатия клавы он не должен реагировать
         {
             control.enabled = false;
         }
     }

     void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
     {
         if (stream.isWriting)
         {
             stream.SendNext(transform.position);
             stream.SendNext(transform.rotation);
         }
         else
         {
             t=0;
             oldPos=newPos;
             oldRot=newRot;
             newPos = (Vector3)stream.ReceiveNext();
             newRot = (Quaternion)stream.ReceiveNext();
         }
     }

     private Vector3 oldPos = Vector3.zero;
     private Quaternion oldRot = Quaternion.identity;
     private Vector3 newPos = Vector3.zero;
     private Quaternion newRot = Quaternion.identity;
     private float t=0;

     void Update()
     {
         if (!photonView.isMine)
         {
             t+=Time.deltaTime*10;//(количество обновлений фотона в секунду, по умолчанию 10)
             transform.position = Vector3.Lerp(oldPos, newPos, t);
             transform.rotation = Quaternion.Lerp(oldRot, newRot, t);
         }
     }
}

Если так? Из-за переменных лагов должен дергаться несильно, но по нормальным позициям.

С таким скриптом должен скакать по точкам 10 раз в секунду, никакого сглаживания:
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class ThirdPersonNetwork : Photon.MonoBehaviour
{
     Control control;//скрипт, где управление

     void Awake()
     {
         control = GetComponent<Control>();
     }
     void Start()
     {
         if (!photonView.isMine)//если чужой персонаж, на нажатия клавы он не должен реагировать
         {
             control.enabled = false;
         }
     }

     void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
     {
         if (stream.isWriting)
         {
             stream.SendNext(transform.position);
             stream.SendNext(transform.rotation);
         }
         else
         {
             transform.position = (Vector3)stream.ReceiveNext();
             transform.rotation = (Quaternion)stream.ReceiveNext();
         }
     }
}
Музыка и звуковой дизайн для игр
Bomb Heroes - Бомбермен онлайн
ximael
UNец
 
Сообщения: 36
Зарегистрирован: 20 апр 2013, 00:23

Re: Vector3.Lerp помогите разобраться.

Сообщение Dantalian 08 авг 2013, 19:34

ximael писал(а):Если так? Из-за переменных лагов должен дергаться несильно, но по нормальным позициям.


Так позиция второго игрока не несменяема он всегда находиться на (0,0,0) хоть на своем экране он и двигается.


ximael писал(а):Как не движутся? В одиночном режиме должны двигаться.


Я допустил ошибку вставил один скрипт 2 раза вот при этом не движется.

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class ThirdPersonNetwork : Photon.MonoBehaviour {
       
        public double interpolationBackTime = 0.1;
       
        internal struct  State
        {
                internal double timestamp;
                internal Vector3 pos;
                internal Quaternion rot;
        }

        // We store twenty states with "playback" information
        State[] m_BufferedState = new State[20];
        // Keep track of what slots are used
        int m_TimestampCount;
       
        void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
        {
                // Always send transform (depending on reliability of the network view)
                if (stream.isWriting)
                {
                        Vector3 pos = transform.localPosition;
                        Quaternion rot = transform.localRotation;
                        stream.Serialize(ref pos);
                        stream.Serialize(ref rot);
                }
                // When receiving, buffer the information
                else
                {
                        // Receive latest state information
                        Vector3 pos = Vector3.zero;
                        Quaternion rot = Quaternion.identity;
                        stream.Serialize(ref pos);
                        stream.Serialize(ref rot);
                       
                        // Shift buffer contents, oldest data erased, 18 becomes 19, ... , 0 becomes 1
                        for (int i=m_BufferedState.Length-1;i>=1;i--)
                        {
                                m_BufferedState[i] = m_BufferedState[i-1];
                        }
                       
                        // Save currect received state as 0 in the buffer, safe to overwrite after shifting
                        State state;
                        state.timestamp = info.timestamp;
                        state.pos = pos;
                        state.rot = rot;
                        m_BufferedState[0] = state;
                       
                        // Increment state count but never exceed buffer size
                        m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);

                        // Check integrity, lowest numbered state in the buffer is newest and so on
                        for (int i=0;i<m_TimestampCount-1;i++)
                        {
                                if (m_BufferedState[i].timestamp < m_BufferedState[i+1].timestamp)
                                        Debug.Log("State inconsistent");
                        }
                       
                        //Debug.Log("stamp: " + info.timestamp + "my time: " + Network.time + "delta: " + (Network.time - info.timestamp));
                }
        }
       
        // This only runs where the component is enabled, which is only on remote peers (server/clients)
        void Update () {
                double currentTime = Network.time;
                double interpolationTime = currentTime - interpolationBackTime;
                // We have a window of interpolationBackTime where we basically play
                // By having interpolationBackTime the average ping, you will usually use interpolation.
                // And only if no more data arrives we will use extrapolation
               
                // Use interpolation
                // Check if latest state exceeds interpolation time, if this is the case then
                // it is too old and extrapolation should be used
                if (m_BufferedState[0].timestamp > interpolationTime)
                {
                        for (int i=0;i<m_TimestampCount;i++)
                        {
                                // Find the state which matches the interpolation time (time+0.1) or use last state
                                if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount-1)
                                {
                                        // The state one slot newer (<100ms) than the best playback state
                                        State rhs = m_BufferedState[Mathf.Max(i-1, 0)];
                                        // The best playback state (closest to 100 ms old (default time))
                                        State lhs = m_BufferedState[i];
                                       
                                        // Use the time between the two slots to determine if interpolation is necessary
                                        double length = rhs.timestamp - lhs.timestamp;
                                        float t = 0.0F;
                                        // As the time difference gets closer to 100 ms t gets closer to 1 in
                                        // which case rhs is only used
                                        if (length > 0.0001)
                                                t = (float)((interpolationTime - lhs.timestamp) / length);
                                       
                                        // if t=0 => lhs is used directly
                                        transform.localPosition = Vector3.Lerp(lhs.pos, rhs.pos, t);
                                        transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
                                        return;
                                }
                        }
                }
                // Use extrapolation. Here we do something really simple and just repeat the last
                // received state. You can do clever stuff with predicting what should happen.
                else
                {
                        State latest = m_BufferedState[0];
                       
                        transform.localPosition = latest.pos;
                        transform.localRotation = latest.rot;
                }
        }
}


Вот скрипт соединения, может пригодиться.

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class NetworkManager : Photon.MonoBehaviour {

        // Use this for initialization
        void Start () {
       
           PhotonNetwork.ConnectUsingSettings("Alpha 0.1");
           
               
        }
        void OnGUI() {
       
                GUILayout.Label (PhotonNetwork.connectionStateDetailed.ToString());
               
        }      
       
        void OnJoinedLobby(){
               
                PhotonNetwork.JoinRandomRoom();
               
        }
       
        void OnPhotonRandomJoinFailed() {
       
                PhotonNetwork.CreateRoom(null);
               
        }
       
        void OnJoinedRoom() {
       
                GameObject ship = PhotonNetwork.Instantiate( "ship" , Vector3.zero *5f , Quaternion.identity , 0 );
                Camera.main.GetComponent<CameraController>().target = ship.transform;
               
        }
       
}
 
Dantalian
UNец
 
Сообщения: 9
Зарегистрирован: 20 ноя 2012, 13:53

Re: Vector3.Lerp помогите разобраться.

Сообщение ximael 08 авг 2013, 20:49

Вроде бы, все норм дб. Глубокий дебаг нужен. Отслеживай переменные, что присылает в OnPhotonSerializeView и далее.
Музыка и звуковой дизайн для игр
Bomb Heroes - Бомбермен онлайн
ximael
UNец
 
Сообщения: 36
Зарегистрирован: 20 апр 2013, 00:23

Re: Vector3.Lerp помогите разобраться.

Сообщение frozencat 03 сен 2014, 23:57

Некропост. Но может кому поможет. т.к. сам искал "что я делаю не так" по тегам, да и четкого ответа нет

unity onphotonserializeview не работает / не вызывается / not firing / not called / not work

ошибка в понимании возникает у тех кто кидает в Observe сам префаб (трансформ), а потом пытается синхронизировать параметры, да и даже сам transform.position, при этом сохраняется видимость благополучия, т.к. РПЦ проходят, и даже сам по себе объект благополучно двигается на всех клиентах, но никакие свойства по onphotonserializeview не синхронизируются и сам onphotonserializeview не вызывается.

Что бы начал работать onphotonserializeview на содержащий его компонент драг-н-дропать в окно Observe.

(т.е. берем компонент заранее прикрепленный к префабу и цепляем его к обзерверу)
frozencat
UNец
 
Сообщения: 24
Зарегистрирован: 03 авг 2014, 18:21

Re: Vector3.Lerp помогите разобраться.

Сообщение sledo 08 ноя 2014, 18:15

frozencat писал(а):Некропост. Но может кому поможет. т.к. сам искал "что я делаю не так" по тегам, да и четкого ответа нет

unity onphotonserializeview не работает / не вызывается / not firing / not called / not work

ошибка в понимании возникает у тех кто кидает в Observe сам префаб (трансформ), а потом пытается синхронизировать параметры, да и даже сам transform.position, при этом сохраняется видимость благополучия, т.к. РПЦ проходят, и даже сам по себе объект благополучно двигается на всех клиентах, но никакие свойства по onphotonserializeview не синхронизируются и сам onphotonserializeview не вызывается.

Что бы начал работать onphotonserializeview на содержащий его компонент драг-н-дропать в окно Observe.

(т.е. берем компонент заранее прикрепленный к префабу и цепляем его к обзерверу)

Переведу на русский то что хотел сказать frozencat.

Если у вас случилось так, что использование скрипта NetworkCharacter, приводит к еще большим лагам видимого игрока (или что там у вас требует синхронизации), или вообще обнуляет позицию его позицию (Vector3(0,0,0)), то это значит у вас не вызывается функция OnPhotonSerializeView в NetworkCharacter. Это происходит от того, что когда вы добавили компонент Photon View на игрока, то в поле Observe: перенесли ваш префаб игрока, а надо было туда перенести как раз таки компонент NetworkCharacter, который висит (или еще не висит) на вашем игроке, на которого вы вешали Photon View.
Лечим больного: Щелкаем на префабе нужного игрока (или кто там у вас требует синхронизации), щелкаем на компоненте NetworkCharacter и тащим его в поле Observe у Photon View. Верность лечения, должна подтвердится в виде измененного значка с Transform на значок скрипта в поле Observe у Photon View. Так же после Observe в скобочках, появится что конкретно находится в поле. Должно быть - (NetworkCharacter) вместо названия префаба.
sledo
Старожил
 
Сообщения: 831
Зарегистрирован: 05 янв 2014, 15:44


Вернуться в Photon

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1