快速而简单。如何从传感器获取四元数据? 基本上我需要:
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
}
我得到一个索引超出绑定的异常,因为值里面只有3个值。根据这个页面: http://developer.android.com/guide/topics/sensors/sensors_motion.html 应该有4个值,还是我理解错误?
答案 0 :(得分:5)
SensorManager
类提供了一个帮助函数来转换:
SensorManager.getQuaternionFromVector(Q, values);
float[] quaternion_w = Q[0];
float[] quaternion_x = Q[1];
float[] quaternion_y = Q[2];
float[] quaternion_z = Q[3];
答案 1 :(得分:2)
getOrientation 的Android实现返回 getQuaterionFromVector 的相同值。 因此,如果需要,您可以获取这些值并构造四元数;
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();
}
}