iphone - 苹果陀螺仪示例代码

标签 iphone cocoa-touch ios4

我计划开发一个基于陀螺仪的项目,例如使用陀螺仪数据旋转opengl纹理,苹果是否发布了有关陀螺仪的示例代码或任何有关将陀螺仪与openGL集成的教程...我搜索谷歌我没有找到任何东西,除了core motion guideevent handling guide .

更新:如果有可用的示例,请告诉我..

最佳答案

要获取陀螺仪更新,您需要创建一个运动管理器对象和可选(但推荐)的引用姿态对象

因此,在您的接口(interface)定义中添加:

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

关于iphone - 苹果陀螺仪示例代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3245733/

相关文章:

iphone - iOS5 的 PJSIP 编译错误

iphone - 从 GCD 后台队列添加到 UIManagedDocument?

iphone - 取消 UILocalNotification

iphone - 在 iOS 中为视频幻灯片而不是图像使用 Open Cover Flow

ios - iOS 7 上的全屏 UIViewController

iphone - Cocoa Touch 捕获/记录/诊断崩溃的最佳实践

iphone - 动画调整 UIButton 的宽度

ios - 选择单元格时如何获取节标题 View 的标题

iphone - 将 block 闭包存储为 IBAction

iphone - 丢失导航 Controller 如何打开另一个 View