Noticias

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

Compass & Heading

Iniciado por iRobb, Octubre 01, 2015, 07:36:21 PM

Tema anterior - Siguiente tema
Octubre 04, 2015, 09:57:55 AM #15 Ultima modificación: Octubre 04, 2015, 10:08:35 AM por Oak Human Flesh
Justamente, Unity recibe la señal del sensor de flujo magnético con muchísima interferencia y no la atenúa, luego cree unas funciones para atenuar algo la señal que le paso al puntero de una brújula de pruebas, esto disminuyendo la velocidad del puntero al acercarse al heading que debe mostrar.tal vez si no leo una vez por frame la señal se estabilice mas.ese ruido hace que la indicación oscile a veces unos 10 grados,  estoy pensando seriamente lo del Filtro de Kalman, sin embargo nunca he hecho tal cosa CompassOakAndroid.apk
Cita de: iRobb date=1443898649" data-ipsquote="" data-cite="iRobb Que me falta ahora... Pues rotar el minimap basándome en el giroscopio, obteniendo valores puntuales del compass que sean coherentes para corregir la rotación. En ello estoy. Si lo consigo, tendré un compass tremendamente fiable y prácticamente sin interferencias de campos magnéticos. 
si creas un sistema de navegación sin usar el flujo magnético, Incluso serviría para navegar cerca de los polos... los aviones que navegan cerca de los polos se desconectan de la señal entregada por sensores de flujo magnético, esto debido a el desorden que existe en las líneas de fuerza del flujo magnético terrestre a altas latitudes.
En los sistemas mas avanzados de navegación en aviación comercial se usan los inerciales, los cuales poseen sensores con laser... son capaces hasta de calcular la velocidad de rotación de la tierra durante un tiempo de inicialización que esta entre unos 7 a 10 minutos, luego a estos se les entrega la posición inicial (de GPS o manualmente) y desde ahi comienzan a navegar por si mismos (sin GPS) usando una base de datos que contiene un mapa mundial y sus GyroLaser, acelerómetros y quien sabe que mas escondido

Bye Bye



Vale, te cuento. No te lo vas a creer. Estaba con código que compensa el compass, el giróscopo, bla bla. No había manera, ninguna de que fuera algo fiable. Había tomado nota de donde estaba el N antes con el maps. Nada encender y apagarlo. Y como estaba ya totalmente mosca, me he instalado una brújula. Nada. No funcionaba tampoco. Daba los mismo giros que en mi código a lo loco. Y pienso, esto ya es de manicomio.Busco por Internet y... el Samsung S4 no viene con el compass calibrado de fábrica. Hay un montón de vídeos que te explican como hacerlo con una app gratuita. Lo saco de la funda, calibro y pam! Brújula funcionando. Te lo puedes creer? Siempre me ha estado funcionando el código. Donde está el icono de llorar, pues este 

Octubre 05, 2015, 03:09:52 AM #17 Ultima modificación: Octubre 05, 2015, 03:12:08 AM por iRobb
Luego de un rato, ha dejado de funcionar. Así que he repasado mi proceso, paso por paso. No es solamente el calibrado (o a lo mejor ni ha influido) sino, la funda! Meter el móvil en la funda con gps, compass, acelerómetro, bla bla bla es una auténtica barbaridad.Como lo saqué de la funda para calibrarlo, pensé que era eso. Al volverlo a meter y probar, todo mal. Y pensando, pues, la fuuuuundaaaaaaa de los chinos (realmente es de El Corte Inglés, pero es que parece de los chinos). Ahora he probado, reprobado y creo que lo tengo comprobado.Y lo bestial es que ahora, al mover arriba y abajo (y) no me afecta en la z. Te puedes creer como de increíble ha cambiado todo. Antes en la funda, mueves en un eje y te afecta a todos, sea acelerómetro, compass o lo que quieras. Por eso no entendía ni papa.
De todos modos, no todo ha sido tiempo perdido. Al final hice el código de compass con compensación por giroscopio, o sea, no tomo el truehading a saco y ya está. Eso ayuda a compensar movimientos bruscos a través del giroscopio y que no le afecten al compass, sino suave con un slerp.

Octubre 05, 2015, 03:19:13 AM #18 Ultima modificación: Octubre 05, 2015, 03:20:22 AM por Oak Human Flesh
Yo acabo de probar mi aplicación a campo traviesa y funciona perfectamente,  pero no hago más que  acercarme a un edificio o dentro de mi automóvil y apunta a cualquier parte, es muy susceptible a interferencias. 
Dentro del automóvil apunta hacia mi radio, le encanta la música 
Dentro del automóvil apunta hacia mi radio, le encanta la música 
Y por que salio dos veces eso?
En otras palabras funciona como un compás magnético
Por que ya se me esta ocurriendo instanciar un objeto en la posición del norte y usarlo para el heading.

Bye Bye



Claro, es eso. Utilizas los tres ejes para rotar o solo en z? Que te paso el código de rotación.

Solo roto usando el eje Y,
void PointerMotion (Transform pointerRx, Vector3 pointerRotationRx)
{
   smoothSpeed = Mathf.DeltaAngle(pointerRx.localEulerAngles.y, pointerRotationRx.y);
   if (smoothSpeed < 0) {
      smoothSpeed *= -1;
   }

   smoothSpeed *= pointerSpeed;
   if (smoothSpeed < nullPointerRange) {
      smoothSpeed = nullPointerSpeed;
   }
   // Orient at the pointerRx
   pointerRx.localRotation =
      Quaternion.Euler(pointerRotationRx.x,
           Mathf.MoveTowardsAngle(pointerRx.localEulerAngles.y, pointerRotationRx.y, smoothSpeed * Time.deltaTime),
           pointerRotationRx.z);
}
pero se ve que es fácilmente modificable

Bye Bye



Lo encontré en Internet e hice mis variaciones. Siempre comento en inglés. Está adaptado para que rote en z con el eje y. Eso lo verás fácil.Está un poco guarri porqué lo hice esta noche y tal como funcionó lo dejé de cara a mañana.
    private void Update() {
        // The gyro is very effective for high frequency movements, but drifts its
        // orientation over longer periods, so we want to use the compass to correct it.
        // The iPad's compass has low time resolution, however, so we let the gyro be
        // mostly in charge here.

        // First we take the gyro's orientation and make a change of basis so it better
        // represents the orientation we'd like it to have
        Quaternion gyroOrientation = Quaternion.Euler(90, 0, 0) * Input.gyro.attitude * Quaternion.Euler(0, 0, 90);

        // See if the compass has new data
        if (Input.compass.timestamp > _lastCompassUpdateTime) {
            _lastCompassUpdateTime = Input.compass.timestamp;

            // Work out an orientation based primarily on the compass
            Vector3 gravity = Input.gyro.gravity.normalized;
            Vector3 flatNorth = Input.compass.rawVector - Vector3.Dot(gravity, Input.compass.rawVector) * gravity;
            _compassOrientation = Quaternion.Euler(180f, 0f, 0f) * Quaternion.Inverse(Quaternion.LookRotation(flatNorth, -gravity)) * Quaternion.Euler(0f, 0f, 90f);

            // Calculate the target correction factor
            _targetCorrection = _compassOrientation * Quaternion.Inverse(gyroOrientation);
        }

        // Jump straight to the target correction if it's a long way; otherwise, slerp towards it very slowly
        if (Quaternion.Angle(_correction, _targetCorrection) > 45f)
            _correction = _targetCorrection;
        else
            _correction = Quaternion.Slerp(_correction, _targetCorrection, 0.02f);

        // Easy bit :)
        Quaternion q = _correction * gyroOrientation;
        // Only y value and 90 degrees. Can change before, but I prefer to do it afterwards. No correction is like a compass holding
        this.transform.localEulerAngles = new Vector3(0f, 0f, q.eulerAngles.y - 90f);

        //this.txtDebug.text = _compassOrientation.eulerAngles.ToString();
    }
 
Como puedes ver se calcula la orientación en base a un punto N y se aplica la corrección por gravedad. El rawVector es el magnetómetro. De este modo el up/down queda corregido. Y si el giro es superior a 45 pues el slerp. Si quieres todos los ejes, no apliques 0's al Vector3 del localrotation.Es muy estable.
Y los -90f son para tenerlo de cara (o sea en vertical). Si lo quieres en horizontal, elimina los -90f.

Como inicializas el valor de _correction?

Bye Bye



Perdón. Todos son identities:   private double _lastCompassUpdateTime = 0;
    private Quaternion _correction = Quaternion.identity;
    private Quaternion _targetCorrection = Quaternion.identity;
    private Quaternion _compassOrientation = Quaternion.identity; 

lo sospechaba, pero pensé que aplicabas una corrección diferente de 0. //this.transform.localEulerAngles = new Vector3(0f, 0f, q.eulerAngles.y - 90f);
   pointer2.localEulerAngles = new Vector3(0f, q.eulerAngles.y - 90f, 0f);Tks   

Bye Bye



Octubre 05, 2015, 06:25:44 AM #25 Ultima modificación: Octubre 05, 2015, 06:28:35 AM por Oak Human Flesh
Jajajaj me acabo d enterar que mi teléfono no tiene Sensor Gyroscopico , por lo cual el puntero 2 constantemente apunta a los 270 grados, el puntero 1 no se vio afectado y sigue funcionando tal como siempre.
aquí queda el Apk que cree para la posteridad
http://unityspain.com/applications/core/interface/file/attachment.php?id=8535">CompassiRobbOakAndroid.apk

Bye Bye




Un poco mejor:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class cGyroManager : MonoBehaviour {
    [Tooltip("Below this angle a slerp will be done otherwise straight forward")]
    public float angleSlerp = 45f;
    [Tooltip("t value for Slerp")]
    [Range(0f, 1f)]
    public float angleSlerpClamp = 0.02f;
    public Text txtDebug;
   
    private bool _enable;

    private double _lastCompassUpdateTime = 0;
    private Quaternion _correction = Quaternion.identity;
    private Quaternion _targetCorrection = Quaternion.identity;
    private Quaternion _compassOrientation = Quaternion.identity;
    private Quaternion _gyroOrientation = Quaternion.identity;
    private Quaternion _finalOrientation = Quaternion.identity;
    private Vector3 _flatNorth;
    private Vector3 _gravity;
   
    /// <summary>
    ///  Method to initalize the gyro at start of game
    /// </summary>
    private void Start() {
        this._enable = false;
    }

    public bool enable {
        get { return (this._enable); }
        set { this._enable = value; }
    }

    private void Update() {
        if (this._enable == true) {
            this.set();
        }
    }

    public Vector3 flatNorth {
        get { return (this._flatNorth); }
    }

    public Vector3 gravity {
        get { return (this._gravity); }
    }

    public Quaternion compassOrientation {
        get { return (this._compassOrientation); }
    }

    public Quaternion gyroOrientation {
        get { return (this._gyroOrientation); }
    }

    private void set() {
        // The gyro is very effective for high frequency movements, but drifts its
        // orientation over longer periods, so we want to use the compass to correct it.
        // The iPad's compass has low time resolution, however, so we let the gyro be
        // mostly in charge here.

        // First we take the gyro's orientation and make a change of basis so it better
        // represents the orientation we'd like it to have
        this._gyroOrientation = Quaternion.Euler(90f, 0f, 0f) * Input.gyro.attitude * Quaternion.Euler(0f, 0f, 90f);

        // See if the compass has new data
        if (Input.compass.timestamp > this._lastCompassUpdateTime) {
            this._lastCompassUpdateTime = Input.compass.timestamp;

            // Work out an orientation based primarily on the compass
            this._gravity = Input.gyro.gravity.normalized;
            this._flatNorth = Input.compass.rawVector - Vector3.Dot(this._gravity, Input.compass.rawVector) * this._gravity;
            this._compassOrientation = Quaternion.Euler(180f, 0f, 0f) * Quaternion.Inverse(Quaternion.LookRotation(this._flatNorth, -this._gravity)) * Quaternion.Euler(0f, 0f, 90f);

            // Calculate the target correction factor
            this._targetCorrection = this._compassOrientation * Quaternion.Inverse(this._gyroOrientation);
        }

        // Jump straight to the target correction if it's a long way; otherwise, slerp towards it very slowly
        if (Quaternion.Angle(this._correction, this._targetCorrection) > this.angleSlerp)
            this._correction = _targetCorrection;
        else
            this._correction = Quaternion.Slerp(this._correction, this._targetCorrection, this.angleSlerpClamp);

        // Easy bit :)
        this._finalOrientation = this._correction * this._gyroOrientation;
        // Only y value and 90 degrees. Can change before, but I prefer to do it afterwards. No correction is like a compass holding
        this.transform.localEulerAngles = new Vector3(0f, 0f, this._finalOrientation.eulerAngles.y - 90f);

        //this.txtDebug.text = this.flatNorth.ToString();
    }
}
 

Octubre 05, 2015, 02:34:42 PM #28 Ultima modificación: Octubre 05, 2015, 02:35:33 PM por Oak Human Flesh
[quote author=iRobb" data-ipsquote-contapp="forums" data-ipsquote-contenttype="forums" data-ipsquote-contentclass="forums_Topic" data-ipsquote-contentid="27938" data-ipsquote-contentcommentid="116123">Un poco mejor:
using UnityEngine;using UnityEngine.UI;
using System.Collections;

public class cGyroManager : MonoBehaviour {
    [Tooltip("Below this angle a slerp will be done otherwise straight forward")]
    public float angleSlerp = 45f;
    [Tooltip("t value for Slerp")]
    [Range(0f, 1f)]
    public float angleSlerpClamp = 0.02f;
    public Text txtDebug;
   
    private bool _enable;

    private double _lastCompassUpdateTime = 0;
    private Quaternion _correction = Quaternion.identity;
    private Quaternion _targetCorrection = Quaternion.identity;
    private Quaternion _compassOrientation = Quaternion.identity;
    private Quaternion _gyroOrientation = Quaternion.identity;
    private Quaternion _finalOrientation = Quaternion.identity;
    private Vector3 _flatNorth;
    private Vector3 _gravity;
   
    /// <summary>
    ///  Method to initalize the gyro at start of game
    /// </summary>
    private void Start() {
        this._enable = false;
    }

    public bool enable {
        get { return (this._enable); }
        set { this._enable = value; }
    }

    private void Update() {
        if (this._enable == true) {
            this.set();
        }
    }

    public Vector3 flatNorth {
        get { return (this._flatNorth); }
    }

    public Vector3 gravity {
        get { return (this._gravity); }
    }

    public Quaternion compassOrientation {
        get { return (this._compassOrientation); }
    }

    public Quaternion gyroOrientation {
        get { return (this._gyroOrientation); }
    }

    private void set() {
        // The gyro is very effective for high frequency movements, but drifts its
        // orientation over longer periods, so we want to use the compass to correct it.
        // The iPad's compass has low time resolution, however, so we let the gyro be
        // mostly in charge here.

        // First we take the gyro's orientation and make a change of basis so it better
        // represents the orientation we'd like it to have
        this._gyroOrientation = Quaternion.Euler(90f, 0f, 0f) * Input.gyro.attitude * Quaternion.Euler(0f, 0f, 90f);

        // See if the compass has new data
        if (Input.compass.timestamp > this._lastCompassUpdateTime) {
            this._lastCompassUpdateTime = Input.compass.timestamp;

            // Work out an orientation based primarily on the compass
            this._gravity = Input.gyro.gravity.normalized;
            this._flatNorth = Input.compass.rawVector - Vector3.Dot(this._gravity, Input.compass.rawVector) * this._gravity;
            this._compassOrientation = Quaternion.Euler(180f, 0f, 0f) * Quaternion.Inverse(Quaternion.LookRotation(this._flatNorth, -this._gravity)) * Quaternion.Euler(0f, 0f, 90f);

            // Calculate the target correction factor
            this._targetCorrection = this._compassOrientation * Quaternion.Inverse(this._gyroOrientation);
        }

        // Jump straight to the target correction if it's a long way; otherwise, slerp towards it very slowly
        if (Quaternion.Angle(this._correction, this._targetCorrection) > this.angleSlerp)
            this._correction = _targetCorrection;
        else
            this._correction = Quaternion.Slerp(this._correction, this._targetCorrection, this.angleSlerpClamp);

        // Easy bit :)
        this._finalOrientation = this._correction * this._gyroOrientation;
        // Only y value and 90 degrees. Can change before, but I prefer to do it afterwards. No correction is like a compass holding
        this.transform.localEulerAngles = new Vector3(0f, 0f, this._finalOrientation.eulerAngles.y - 90f);

        //this.txtDebug.text = this.flatNorth.ToString();
    }
}
 [/quote]Mucho mas ordenado , pero sigo sin giroscopio, mi teléfono no tiene el hardware, existirá una solución para la compensación?, voy a buscar por ahí,  ya que tengo un GPS que funciona perfecto, pero tengo que empezar a moverme para que calcule bien la dirección.

Bye Bye



Me la he instalado y probado tu app, y no me da la misma orientación al N. Me da como unos 20 grados este respecto al N (no magnético).

Etiquetas: