SW Jeong
SW Jeong

Reputation: 168

Rendering orientation of an object with quaternion in Unity

I am trying to render quaternion data calculated from 9DOF data coming out from a single IMU.

However, I could not find an explicit and simple example for this C# script. Here is my code so far but it seems that the object shown in unity keeps juggling in one direction.

Here is the code. I wish to know what I am getting wrong here.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.IO;
using System;

public class Motion : MonoBehaviour {
public float speed = 0.00001f;
public float x;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    x += Time.deltaTime * 10;
    // transform.Translate(-Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0);
    // transform.rotation = Quaternion.Euler(x, 0, 0);

    var reader = new StreamReader(@"F:\MovTrack\C++ Implementation Sensor Fusion Library\MovTrack_Processor\Sensor Fusion\Sensor Fusion\Q_Output.csv");

    while(!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(',');

        float x = float.Parse(values[0]);
        float y = float.Parse(values[1]);
        float z = float.Parse(values[2]);
        float w = float.Parse(values[3]);

        //Console.Out.WriteLine(x + "  " + y + "   " + z + "  " + w);

        Quaternion q = new Quaternion(x, y, z, w);
        transform.Rotate(q.eulerAngles);
        for(int i = 0; i < 1; i++)
        {

        }
    }
}

}

Upvotes: 0

Views: 409

Answers (1)

derHugo
derHugo

Reputation: 90813

This

Quaternion q = new Quaternion(x, y, z, w);
transform.Rotate(q.eulerAngles);

is not a good idea. While the direction from Euler to Quaternion allways works in Quaternion.Euler, the other way round from Quaternion to Euler using q.eulerAngles doesn't allways return the same value because a Quaternion can have multiple (maybe infinite?) representations in Euler!

So if you already have a Quaternion (assuming your x, y, z, w values are correct) don't use any Euler.

You do join two rotations by multiplication

quaternionA * quaternionB

(careful different than in e.g. a float multiplication this is a matrix multiplication and therefore the order matters!)


So if you want to add the rotation use

transform.rotation *= q;

if you want to set the rotation simply use

transform.rotation = q;

Upvotes: 2

Related Questions