首先参考维基百科了解四元数的基本概念:
https://zh.wikipedia.org/wiki/%E5%9B%9B%E5%85%83%E6%95%B0%E4%B8%8E%E7%A9%BA%E9%97%B4%E6%97%8B%E8%BD%AC
参考
http://www.2cto.com/kf/201210/162858.html
http://blog.csdn.net/flowingflying/article/details/43451351
http://www.4byte.cn/question/502095/get-quaternion-from-android-gyroscope.html
Android中对传感器类型的定义:
- #define SENSOR_TYPE_ACCELEROMETER 1 //加速度
-
- #define SENSOR_TYPE_MAGNETIC_FIELD 2 //磁力
-
- #define SENSOR_TYPE_ORIENTATION 3 //方向
-
- #define SENSOR_TYPE_GYROSCOPE 4 //陀螺仪
-
- #define SENSOR_TYPE_LIGHT 5 //光线感应
-
- #define SENSOR_TYPE_PRESSURE 6 //压力
-
- #define SENSOR_TYPE_TEMPERATURE 7 //温度
-
- #define SENSOR_TYPE_PROXIMITY 8 //接近
-
- #define SENSOR_TYPE_GRAVITY 9 //重力
-
- #define SENSOR_TYPE_LINEAR_ACCELERATION 10//线性加速度
-
- #define SENSOR_TYPE_ROTATION_VECTOR 11//旋转矢量
native层Sensor.h中没有定义旋转矢量的枚举变量,仅有:
-
-
-
-
-
- enum {
- ASENSOR_TYPE_ACCELEROMETER = 1,
- ASENSOR_TYPE_MAGNETIC_FIELD = 2,
- ASENSOR_TYPE_GYROSCOPE = 4,
- ASENSOR_TYPE_LIGHT = 5,
- ASENSOR_TYPE_PROXIMITY = 8
- };
因此这里用整型11做参数获取旋转矢量:
- appState.engine.sensorManager = ASensorManager_getInstance();
- appState.engine.accelerometerSensor = ASensorManager_getDefaultSensor(
- appState.engine.sensorManager, 11);
- appState.engine.sensorEventQueue = ASensorManager_createEventQueue(
- appState.engine.sensorManager, app->looper, LOOPER_ID_USER, NULL,
- NULL);
再模拟SensorManager.java中的getQuaternionFromVector函数转换成四元数即可(不是很严格,为简单,去掉了rv长度为4的情形)
- void getQuaternionFromVector(float Q[], float rv[]) {
- ALOGV("rv(%f,%f,%f)",rv[0],rv[1],rv[2]);
- Q[0] = 1 - rv[0] * rv[0] - rv[1] * rv[1] - rv[2] * rv[2];
- Q[0] = (Q[0] > 0) ? (float) sqrt(Q[0]) : 0;
- Q[1] = rv[0];
- Q[2] = rv[1];
- Q[3] = rv[2];
- ALOGV("Q(%f,%f,%f,%f)",Q[0],Q[1],Q[2],Q[3]);
- }
转换出来的长度为4的数组Q即为所需四元数。
ps:记得,横竖屏切换的时候传-z,而非z(rotation[2] = -event.vector.z;)