要获得陀螺仪更新,您需要创建一个运动管理器对象和可选(但推荐)一个参考姿态对象
所以在你的接口定义中添加:
CMMotionManager *motionManager;
CMAttitude *referenceAttitude;
根据文档,您应该只为每个应用程序创建这些管理器之一。我建议通过单例使 motionManager 可访问,但如果您只实例化您的类一次,那可能不需要做一些额外的工作。
然后在您的 init 方法中,您应该像这样分配运动管理器对象;
motionManager = [[CMMotionManager alloc] init];
referenceAttitude = nil;
当您想要启用运动更新时,您可以创建一个 enableMotion 方法或仅从 init 方法调用它。下面将存储初始设备姿态并导致设备继续采样陀螺并更新其姿态属性。
-(void) enableMotion{
CMDeviceMotion *deviceMotion = motionManager.deviceMotion;
CMAttitude *attitude = deviceMotion.attitude;
referenceAttitude = [attitude retain];
[motionManager startDeviceMotionUpdates];
}
对于虚拟现实应用程序,使用陀螺仪和 OpenGL 非常简单。
您需要获取当前的陀螺姿态(旋转),然后将其存储在 OpenGL 兼容矩阵中。下面的代码检索并保存当前设备运动。
GLfloat rotMatrix[16];
-(void) getDeviceGLRotationMatrix
{
CMDeviceMotion *deviceMotion = motionManager.deviceMotion;
CMAttitude *attitude = deviceMotion.attitude;
if (referenceAttitude != nil) [attitude multiplyByInverseOfAttitude:referenceAttitude];
CMRotationMatrix rot=attitude.rotationMatrix;
rotMatrix[0]=rot.m11; rotMatrix[1]=rot.m21; rotMatrix[2]=rot.m31; rotMatrix[3]=0;
rotMatrix[4]=rot.m12; rotMatrix[5]=rot.m22; rotMatrix[6]=rot.m32; rotMatrix[7]=0;
rotMatrix[8]=rot.m13; rotMatrix[9]=rot.m23; rotMatrix[10]=rot.m33; rotMatrix[11]=0;
rotMatrix[12]=0; rotMatrix[13]=0; rotMatrix[14]=0; rotMatrix[15]=1;
}
根据您想要做什么,您可能需要反转它,这很容易。
旋转的逆只是它的转置,这意味着交换列和行。
于是上面就变成了:
rotMatrix[0]=rot.m11; rotMatrix[4]=rot.m21; rotMatrix[8]=rot.m31; rotMatrix[12]=0;
rotMatrix[1]=rot.m12; rotMatrix[5]=rot.m22; rotMatrix[9]=rot.m32; rotMatrix[13]=0;
rotMatrix[2]=rot.m13; rotMatrix[6]=rot.m23; rotMatrix[10]=rot.m33; rotMatrix[14]=0;
rotMatrix[3]=0; rotMatrix[7]=0; rotMatrix[11]=0; rotMatrix[15]=1;
如果您想要偏航角、俯仰角和滚动角,那么您可以使用
轻松访问它们
attitude.yaw
attitude.pitch
attitude.roll