代码之家  ›  专栏  ›  技术社区  ›  Chandan Shetty SP

苹果陀螺仪样本代码

  •  30
  • Chandan Shetty SP  · 技术社区  · 15 年前

    我计划开发一个基于陀螺仪的项目,比如旋转 使用陀螺仪数据的OpenGL纹理 ,是否有苹果发布的关于陀螺仪的示例代码,或是关于将陀螺仪与OpenGL集成的教程…我搜索了谷歌除了 core motion guide event handling guide .

    更新:如果有样品,请告诉我。

    4 回复  |  直到 11 年前
        1
  •  58
  •   cooperz twerdster    11 年前

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

    因此,在接口定义中添加:

    CMMotionManager *motionManager;
    CMAttitude *referenceAttitude;
    

    根据文档,每个应用程序只能创建一个这样的管理器。我建议让MotionManager可以通过单个实例访问,但这是一些额外的工作,如果只实例化一次类,则可能不需要做这些工作。

    然后在init方法中,您应该这样分配motion manager对象;

    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
    
        2
  •  15
  •   SamB    14 年前

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

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

        3
  •  5
  •   Michael Behan    15 年前

    核心运动是如何获取陀螺仪数据的。查看CMGyrodata以获取原始数据,或使用设备情感态度和旋转速率属性。

    如果你是注册的苹果开发者,我建议你观看“设备运动”WWDC会话。

    推荐文章