Android获取四元数数据

Android get quaternion data

快速简单。如何从传感器获取四元数数据? 基本上我需要:

float quaternion_x = ?
float quaternion_y = ?
float quaternion_z = ?
float quaternion_w = ?

我有这样的东西:

if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
    float[] values = event.values;

    float quaternion_x = values[0];
    float quaternion_y = values[1];
    float quaternion_z = values[2];
    float quaternion_w = values[3];  <----- ERROR HERE 
}

我得到一个索引超出范围的异常,因为 values 里面只有 3 个值。根据此页面: http://developer.android.com/guide/topics/sensors/sensors_motion.html 应该有 4 个值还是我理解有误?

SensorManager class 提供了一个帮助函数来为您转换:

SensorManager.getQuaternionFromVector(Q, values);
float[] quaternion_w = Q[0];
float[] quaternion_x = Q[1];
float[] quaternion_y = Q[2];
float[] quaternion_z = Q[3];

android 执行 getOrientation returns 与 getQuaterionFromVector[ 相同的值=19=]。 因此,如果需要,您可以采用这些值并构造四元数;

float[] quaternion = new float[4];
quaternion[0] = 0;  //w
quaternion[1] = orientation[0];  //x
quaternion[2] = orientation[1];  //y
quaternion[3] = orientation[2];  //z

我用这个代码查了一下。

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mMagneticField = event.values;
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = event.values;
    if ((mGravity == null) || (mMagneticField == null))
        return;

    float R[] = new float[9];
    float I[] = new float[9];
    boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mMagneticField);
    if (success) {
        mOrientation = new float[3];
        mQuaternion = new float[4];
        SensorManager.getOrientation(R, mOrientation);
        mAzimut = mOrientation[0]; // orientation contains: azimut, pitch and roll
        mPitch = mOrientation[1];
        mRoll = mOrientation[2];

        SensorManager.getQuaternionFromVector(mQuaternion, mOrientation);

        if(mAzimut - mQuaternion[1] == 0 && mPitch - mQuaternion[2] == 0 && mRoll - mQuaternion[3] == 0){
            Log.d("ORIENTATION", "QUATERNION IS THE SAME");
        }
        notifyObservers();
    }
}