Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Resetear posicion waypoint

Iniciado por brok, Enero 08, 2018, 12:12:43 AM

Tema anterior - Siguiente tema
Cita de: brok date=1515441948ya lo tengo
   
   
      


Ahh, disculpa, Queue utiliza Push=Enqueue y Pop=Dequeue

Gracias ya me estaba voviendo loco jajaja mil gracias
Bueno y todo ese código que todavía no entiendo¿ como lo vinculo al que estaba aviendo quitando lo de las corutinas y playerprefas?.

Mira te explico, primero necesitas ir agregando snapshots cada X tiempo, esto lo puedes hacer desde un corrutina, agrega estas dos funciones a la clase SnapshotControl
 

public IEnumerator IRecorder(Transform t)
{
   while(true)
   {
      Register(t);
      yield return new WaitForSecond(.5f);
   }
}
public IEnumerator IPlayback(Transform t)
{
   while(true)
   {
      Snapshot snapshot = Get();
      if(snapshot == null)
         break;
      //Aqui puedes crear una corrutina para la interpolación de los valores.
      t.position = snapshot.Position;
      t.rotation = snapshot.Rotation;
      yield return new WaitForSecond(.5f);
   }
}

 
Luego desde el script del player llamas la corrutina IRecorder cuando quieras grabar y IPlayback cuando quieras volver el tiempo atrás.
 
 
 
 

Que complicado pero me gusta 
Esto es lo que tengo echo e llamado a las corrutinas pero no me funciona: 
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class VuelcoCoche : MonoBehaviour
{
        public Vector3 Posicion;
        private GameObject[] WayPoints;
        private Transform player;
        private int index = -1;
        private float distancia = 100000;
    void Start()
        {
            player = GameObject.FindGameObjectWithTag("Player").transform;
            WayPoints = GameObject.FindGameObjectsWithTag("WaypointVuelco");
           
       
        }
        void Update()
        {
            if (Input.GetKey(KeyCode.R))
            {
                ResetarCoche(Posicion);
               
            }
       
        SnapshotControl sc = new SnapshotControl(index);
        StartCoroutine(sc.IRecorder(player));
        }
       
        Vector3 ResetarCoche(Vector3 pos)
        {
           
           
           
            for (int i = 0; i < WayPoints.Length; i++)
            {
               
                float tmpDistancia = (WayPoints[i].transform.position - pos).magnitude;
               
                if (tmpDistancia < distancia)
                {
                    index = i;
                    distancia = tmpDistancia;
                    SnapshotControl sc = new SnapshotControl(index);
                    StartCoroutine(sc.IPlayback(player));
                   
                   
                }
            }
            return WayPoints[index].transform.position;
           
        }
       
        void OnTriggerEnter(Collider colision)
        {
            if (colision.gameObject.CompareTag("Terreno"))
            {
                ResetarCoche(Posicion);
               
            }
        }
       
       
}
public class Snapshot
{
    public Vector3 Position { get; private set; }
    public Quaternion Rotation { get; private set; }
    public Snapshot(Vector3 pos, Quaternion rot)
    {
        Position = pos;
        Rotation = rot;
    }
}
public class SnapshotControl
{
    private Queue<Snapshot> _snapshots = new Queue<Snapshot>();
    private int _maxSnapshots = 200;
    public SnapshotControl(int max)
    {
        _maxSnapshots = max;
    }
    public void Register(Transform t)
    {
        _snapshots.Enqueue(new Snapshot(t.position, t.rotation));
        if (_snapshots.Count > _maxSnapshots)
            _snapshots.Dequeue();
    }
    public Snapshot Get()
    {
        if (_snapshots.Count > 0)
            return _snapshots.Dequeue();
        return null;
    }
 
    public void Clear()
    {
        _snapshots.Clear();
    }
    public IEnumerator IRecorder(Transform t)
    {
        while (true)
        {
            Register(t);
            yield return new WaitForSeconds(0.5f);
        }
    }
    public IEnumerator IPlayback(Transform t)
    {
        while (true)
        {
            Snapshot snapshot = Get();
            if (snapshot == null)
                break;
            //Aqui puedes crear una corrutina para la interpolación de los valores.
            t.position = snapshot.Position;
            t.rotation = snapshot.Rotation;
            yield return new WaitForSeconds(0.5f);
        }
    }
}

 
No lo estoy haciendo bien ¿verdad?.

al final donde pone //Aqui puedes crear una corrutina para la interpolación de los valores.

dendro de una corritina se puede hacer otra no lo entiendo.

Estas implementando todo mal, presta atención, ¿Cómo vas a poner SnapshotControl dentro del Update? -

Bueno pues no se hacerlo tendre que aprender mas de programación ya que no soy del todo programador mil gracias de todas formas.

Quien me solucione el problema prometo que le ayudare en algo de diseño o animación 3d.

Cita de: francoe1 date=1515407922A ver, lo tenes que hacer es un arreglo de WayPoints este mismo puede ser de tipo transform, a cada WayPoints le agregas un TAG especial para identificarlos, luego desde una función awake asignas el arreglo.
   
   
       
   
   

public class WayPointManager : MonoBehaviour
{
    private GameObject[] _waypoints;
private void Awake()
    {
       _waypoints = GameObject.FindGameObjectsWithTag("WayPoint");
    }
      public Vector3 GetNear(Vector3 from)
      {
         int index = -1;
         float distance = 100000;
         for(int i = 0; i < _waypoints.Length; i++)
         {
            float tmpdistance = (_waypoints.transform - from).magnitude;
            if(tmpdistance < distance)
            {
               index = i;
               distance = tmpdistance;
            }
         }
         return _waypoints[index].transform.position;
      }
}

   
      De esa manera podes hacerlo ...
   


francoe1 eres un maquina total mil gracias funcionaba este código solo que no me di cuenta que el waypoint mas cercano estaba casi al final mil gracias ya que esta solucionado y te as esmerado mucho pideme algo de diseño 3d o animación 3d y te lo hago, que contento estoy tio, genial.
 
Todabia no funciona del todo bien pero funciona por lo visto recorre la lista de waipoint cada vez que vuelco o pulso la r porque se a quedado de lado y busca el primer waypoint de la lista y no el mas cercano, tengo que darle tiempo para que le de tiempo de recorrer la lista y encontrar el mas cercano.

Esto es lo que tengo echo:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class VuelcoCoche : MonoBehaviour
{
   
    private Transform player;
    private GameObject[] wayPoints;
    private int Index = -1;
    private Vector3 posicion;
   
    void Start()
    {
        wayPoints = GameObject.FindGameObjectsWithTag("WaypointVuelco");
       
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            ResetarPosicionCoche(posicion);
           
        }
    }
    void OnTriggerEnter(Collider colision)
    {
        if (colision.gameObject.CompareTag("Terreno"))
        {
            ResetarPosicionCoche(posicion);
           
        }
    }
    Vector3 ResetarPosicionCoche(Vector3 fromV)
    {
       
        int index = -1;
        float distance = 100000;
 
        for (int i = 0; i < wayPoints.Length; i++)
        {
            float tmpdistance = (wayPoints[i].transform.position - fromV).magnitude;
            if (tmpdistance < distance)
            {
                index = i;
                player.transform.position = wayPoints[index].transform.position;
                player.transform.rotation = Quaternion.LookRotation(player.transform.position, transform.position);
                distance = tmpdistance;
            }
           
        }
        return wayPoints[index].transform.position;
    }
   
 
}

 
 

Cita de: brok date=1515478817Esto es lo que tengo echo:
   
   

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class VuelcoCoche : MonoBehaviour
{
   
    private Transform player;
    private GameObject[] wayPoints;
    private int Index = -1;
    private Vector3 posicion;
   
    void Start()
    {
        wayPoints = GameObject.FindGameObjectsWithTag("WaypointVuelco");
       
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            ResetarPosicionCoche(posicion);
           
        }
    }
    void OnTriggerEnter(Collider colision)
    {
        if (colision.gameObject.CompareTag("Terreno"))
        {
            ResetarPosicionCoche(posicion);
           
        }
    }
    Vector3 ResetarPosicionCoche(Vector3 fromV)
    {
       
        int index = -1;
        float distance = 100000;
 
        for (int i = 0; i < wayPoints.Length; i++)
        {
            float tmpdistance = (wayPoints[i].transform.position - fromV).magnitude;
            if (tmpdistance < distance)
            {
                index = i;
                player.transform.position = wayPoints[index].transform.position;
                player.transform.rotation = Quaternion.LookRotation(player.transform.position, transform.position);
                distance = tmpdistance;
            }
           
        }
        return wayPoints[index].transform.position;
    }
   
 
}

   
       
   


Para detectar que el coche esté dado vuelta puedes evaluar el ángulo del mismo, si este supera x limite, lanzar varios rayos de manera estratégica y si alguno colisiona por mas de 5 segundos entonces efectivamente estas dado vuelta, esto porque puedes dar un giro de 360 y no lo deberias contar como que el auto esté dado vuelta. 
 
Por otro lado, la funcion que busca el WayPoint no tiene que tener ningun control sobre el transform, esta solo busca y retorna la posición, lo que podríamos hacer es que te retorna la posición más un predicción de la rotación.
 
para esto modificamos la función de la siguiente manera.
 

bool GetNearPoint(Vector3 fromV, out Quaternion rot, out Vector3 pos)
    {
       
        int index = -1;
        float distance = 100000;
        for (int i = 0; i < wayPoints.Length; i++)
        {
            float tmpdistance = (wayPoints[i].transform.position - fromV).magnitude;
            if (tmpdistance < distance)
            {
                index = i;
                distance = tmpdistance;
            }            
        }
   
   if(index >= 0)
   {
      if(index + 1 < wayPoints.Length)
                 rot = Quaternion.Look(wayPoints[index] - wayPoints[index + 1]);
            else
                  rot = Quaternion.Look(wayPoints[index] - from);
            pos = wayPoints[index]
      return true;
   }
        pos = Vector3.zero;
        rot = Quaternion.Identity;
   return false;
    }

 
La página tabula muy mal :( ---
 
Bien ahora para utilizarlo, tendrias que hacer lo siguiente... desde cualquier función, supongamos que es a través del teclado.
 

private void Update()
{
if(Input.GetKeyDown(KeyCore.R))
{
   Vector3 pos;
   QUaternion rot;
   if(GetNearPoint(transform.position, out pos, out rot))
   {
      transform.position = pos;
      transform.rotation = rot;
   }
   else
   {
      Debug.Log("No exist near point..");
   }
}
}

 
Espero te sirva....

Me ha quedado a sin y no funciona lo siento a via unos cuantos errores los he corregido pero nada no funciona y ahora havia borrado todo crellendo que me iva valer bueno no pasa nada mil gracias de nuevo.
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class VuelcoCoche : MonoBehaviour
{
   
   
    private GameObject[] wayPoints;
   
 
    void Start()
    {
        wayPoints = GameObject.FindGameObjectsWithTag("WaypointVuelco");
     
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            Quaternion rot;
            Vector3 pos;
            if (GetNearPoint(transform.position, out rot, out pos))
            {
                transform.position = pos;
                transform.rotation = rot;
            }
            else
            {
                Debug.Log("No exist near point..");
            }
        }
    }
    void OnTriggerEnter(Collider colision)
    {
        if (colision.gameObject.CompareTag("Terreno"))
        {
            Quaternion rot;
            Vector3 pos;
            if (GetNearPoint(transform.position, out rot, out pos))
            {
                transform.position = pos;
                transform.rotation = rot;
            }
            else
            {
               Debug.Log("No exist near point..");
            }
           
 
        }
    }
    bool GetNearPoint(Vector3 fromV, out Quaternion rot, out Vector3 pos)
    {
        int index = -1;
        float distance = 100000;
        for (int i = 0; i < wayPoints.Length; i++)
        {
            float tmpdistance = (wayPoints[i].transform.position - fromV).magnitude;
            if (tmpdistance < distance)
            {
                index = i;
                distance = tmpdistance;
            }
        }
        if (index >= 0)
        {
            if (index + 1 < wayPoints.Length)
                rot = Quaternion.LookRotation(wayPoints[index].transform.position - wayPoints[index + 1].transform.position);
            else
                rot = Quaternion.LookRotation(wayPoints[index].transform.position - fromV);
            pos = wayPoints[index].transform.position;
            return true;
        }
        pos = Vector3.zero;
        rot = Quaternion.identity;
        return false;
    }
}

 
 
 
ya lo arregle

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class VuelcoCoche : MonoBehaviour
{
   
   
    private GameObject[] wayPoints;
    private GameObject player;
 
    void Start()
    {
        wayPoints = GameObject.FindGameObjectsWithTag("WaypointVuelco");
        player = GameObject.FindGameObjectWithTag("Player");
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            Quaternion rot;
            Vector3 pos;
            if (GetNearPoint(transform.position, out rot, out pos))
            {
                transform.position = pos;
                transform.rotation = rot;
            }
            else
            {
                Debug.Log("No exist near point..");
            }
        }
    }
    void OnTriggerEnter(Collider colision)
    {
        if (colision.gameObject.CompareTag("Terreno"))
        {
            Quaternion rot;
            Vector3 pos;
            if (GetNearPoint(transform.position, out rot, out pos))
            {
                transform.position = pos;
                transform.rotation = rot;
            }
            else
            {
               Debug.Log("No exist near point..");
            }
           
 
        }
    }
    bool GetNearPoint(Vector3 fromV, out Quaternion rot, out Vector3 pos)
    {
        int index = -1;
        float distance = 100;
        float tiempo;
        tiempo = Time.time;
        for (int i = 0; i < wayPoints.Length; i++)
        {
            float tmpdistance = (wayPoints[i].transform.position - fromV).magnitude;
            if (tmpdistance < distance)
            {
                if(tiempo > 0)
                {
                    player.transform.position = wayPoints[i].transform.position;
                    index = i;
                    distance = tmpdistance;
                    tiempo = 0;
                    Debug.Log(distance);
                }
               
            }
        }
        if (index >= 0)
        {
            if (index + 1 < wayPoints.Length)
                rot = Quaternion.LookRotation(wayPoints[index].transform.position - wayPoints[index + 1].transform.position);
            else
                rot = Quaternion.LookRotation(wayPoints[index].transform.position - fromV);
            pos = wayPoints[index].transform.position;
            return true;
        }
        pos = Vector3.zero;
        rot = Quaternion.identity;
        return false;
    }
}

 
 

Al final va perfecto a sin he borrado algunas cosas espero que no te moleste y mil gracias de nuevo:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class VuelcoCoche : MonoBehaviour
{
   
   
    private GameObject[] wayPoints;
    private GameObject player;
 
    void Start()
    {
        wayPoints = GameObject.FindGameObjectsWithTag("WaypointVuelco");
        player = GameObject.FindGameObjectWithTag("Player");
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            Quaternion rot;
            Vector3 pos;
            if (GetNearPoint(transform.position, out rot, out pos))
            {
                transform.position = pos;
                transform.rotation = rot;
            }
           
        }
    }
    void OnTriggerEnter(Collider colision)
    {
        if (colision.gameObject.CompareTag("Terreno"))
        {
            Quaternion rot;
            Vector3 pos;
            if (GetNearPoint(transform.position, out rot, out pos))
            {
                transform.position = pos;
                transform.rotation = rot;
            }
           
           
 
        }
    }
    bool GetNearPoint(Vector3 fromV, out Quaternion rot, out Vector3 pos)
    {
        int index = -1;
        float distance = 100;
        float tiempo;
        tiempo = Time.time;
        for (int i = 0; i < wayPoints.Length; i++)
        {
            float tmpdistance = (wayPoints[i].transform.position - fromV).magnitude;
            if (tmpdistance < distance)
            {
                if(tiempo > 0)
                {
                    player.transform.position = wayPoints[i].transform.position;
                    player.transform.rotation = Quaternion.LookRotation(player.transform.forward, player.transform.up);
                    index = i;
                    distance = tmpdistance;
                    tiempo = 0;
                    Debug.Log(distance);
                   
                }
               
                   
                   
               
            }
        }
       
        pos = Vector3.zero;
        rot = Quaternion.identity;
        return false;
    }
}

 
 

Lo dicho fracoe1 cualquier cosa me la dices ok
 
 

Enero 09, 2018, 04:25:31 PM #29 Ultima modificación: Enero 09, 2018, 04:26:08 PM por francoe1
Cita de: brok date=1515508688Lo dicho fracoe1 cualquier cosa me la dices ok
   
       
   


Dale, gracias!
 
 
 
El problema que vi es que estas moviendo el Player Por todos los WayPoints, si bien funciona pero el jugador se recorre todos los WayPoints para esto es la función GetNear para solo obtener 1 opción, la más cercana.
 
Pero mientras te funcione no hay problema, yo no lo haria de esa manera pero tu meta es lograr que funcione y si asi es es más que suficiente!
 
¿Eres el mismo de hace 4 años no?, cuando intentaste hacer un juego de lucha ¿Puede ser...?

Etiquetas: