Apple陀螺仪示例代码

Cha*_* SP 30 iphone cocoa-touch ios4

我正计划开发一个基于陀螺仪的项目,比如使用陀螺仪数据旋转opengl纹理,是否有关于陀螺仪的苹果发布的任何示例代码或任何关于将陀螺仪与openGL集成的教程...我搜索谷歌我除了核心没有找到任何东西动作指南事件处理指南.

更新:如果有任何样品,请告诉我..

twe*_*ter 58

要获得陀螺仪更新,您需要创建一个运动管理器对象,并可选择(但推荐)参考姿态对象

所以在您的界面定义中添加:

CMMotionManager *motionManager;
CMAttitude *referenceAttitude;
Run Code Online (Sandbox Code Playgroud)

根据文档,您应该只为每个应用程序创建一个这样的管理器.我建议通过单例访问motionManager,但如果你只实例化一次类,那么你可能不需要做一些额外的工作.

然后在你的init方法中你应该像这样分配运动管理器对象;

motionManager = [[CMMotionManager alloc] init];
referenceAttitude = nil; 
Run Code Online (Sandbox Code Playgroud)

如果要启用动画更新,可以创建enableMotion方法或仅从init方法调用它.以下将存储初始设备姿态并使设备继续对陀螺仪进行采样并更新其姿态属性.

-(void) enableMotion{
        CMDeviceMotion *deviceMotion = motionManager.deviceMotion;      
        CMAttitude *attitude = deviceMotion.attitude;
        referenceAttitude = [attitude retain];
        [motionManager startDeviceMotionUpdates];
}
Run Code Online (Sandbox Code Playgroud)

对于使用陀螺仪和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;
}
Run Code Online (Sandbox Code Playgroud)

根据您的想法,您可能需要将其反转,这非常容易.旋转的倒数只是它的转置,这意味着交换列和行.所以上面变成了:

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;
Run Code Online (Sandbox Code Playgroud)

如果您想要偏航,俯仰和滚转角度,那么您可以轻松使用它们

attitude.yaw
attitude.pitch
attitude.roll
Run Code Online (Sandbox Code Playgroud)

  • 有没有人知道所有这些代码后,我如何简单地抓住陀螺仪的x,y,z值?只是?没有矩阵和东西? (2认同)

Sam*_*amB 15

我一直在寻找一些示例代码作为一个非常简单的项目.经过几天的搜索,我终于找到了它.你来找你们!

http://cs491f10.wordpress.com/2010/10/28/core-motion-gyroscope-example/


Mic*_*han 5

CoreMotion是如何获取陀螺仪数据的.查看CMGyrodata的原始数据或使用DeviceMotion态度和旋转速率属性.

如果您是注册苹果开发人员,我建议您观看"Device Motion"WWDC会话.

  • 这些视频不需要付费的iPhone开发人员.使用与下载sdk相同的Apple开发者帐户.需要付费会员**才能在实际设备上进行测试.鉴于您的目标是硬件功能,您必须升级. (7认同)