3

我想在我的 iPhone 应用程序中添加来自 cocos3d 的 3D 对象作为增强现实的相机叠加层。我有一些模型的 CC3Scene。我创建了motionManager捕获以获取有关设备摄像头方向的信息,然后在 -(void)update:(ccTime)dt 我尝试更新 cocos3d 场景内摄像头的位置(场景的向上方向是 Z 轴) :

-(void) update:(ccTime)dt
{
    CMDeviceMotion *currentDeviceMotion = motionManager.deviceMotion;
    CMAttitude *currentAttitude = currentDeviceMotion.attitude;

    CC3Camera *cam = (CC3Camera*)[cc3Scene getNodeNamed:@"Camera"];

    static double lastY = 0;
    static double lastP = 0;
    static double lastR = 0;

    double yaw = CC_RADIANS_TO_DEGREES(currentAttitude.yaw-lastY);
    double pitch = CC_RADIANS_TO_DEGREES(currentAttitude.pitch-lastP);
    double roll = CC_RADIANS_TO_DEGREES(currentAttitude.roll-lastR);

    CC3Vector fd = cc3v(0,1,0);
    [cam rotateByAngle:roll aroundAxis:fd];

    CC3Vector rp = cc3v(1,0,0);
    [cam rotateByAngle:pitch aroundAxis:rp];

    CC3Vector up = cc3v(0,0,1);
    [cam rotateByAngle:yaw aroundAxis:up];

lastY = currentAttitude.yaw;
lastP = currentAttitude.pitch;
lastR = currentAttitude.roll;

[super update:dt];
}

我无法直接使用 cam.rotation = cc3v(pitch, roll, yaw) 因为 cocos 中的旋转顺序(使用我当前的轴)与设备中的旋转顺序不匹配。但是我的代码也不能正常工作。手动旋转相机时出错,我不知道应该如何旋转它以使其正确(我已经尝试了几乎所有顺序和轴的组合)。

所以问题是如何匹配 cocos 的相机旋转和设备的旋转?我错过了什么吗?或者您能否提供包含此类主题的代码或教程项目?我知道这是一个相当简单的问题,因为只有三角函数,但我试图做到这一点让我大吃一惊。

谢谢!

4

1 回答 1

1

完成该代码,工作正常

-(CC3Vector4)multiplyQuaternion:(CC3Vector4)q2 onAxis:(CC3Vector4)axis byDegress:(float)degrees{

  CC3Vector4 q1;

  q1.x = axis.x;
  q1.y = axis.y;
  q1.z = axis.z;

  // Converts the angle in degrees to radians.
  float radians = CC_DEGREES_TO_RADIANS(degrees);

  // Finds the sin and cosine for the half angle.
  float sin = sinf(radians * 0.5);
  float cos = cosf(radians * 0.5);

  // Formula to construct a new Quaternion based on direction and angle.
  q1.w = cos;
  q1.x = q1.x * sin;
  q1.y = q1.y * sin;
  q1.z = q1.z * sin;

  // Multiply quaternion, q1 x q2 is not equal to q2 x q1

  CC3Vector4 newQ;
  newQ.w = q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z;
  newQ.x = q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y;
  newQ.y = q1.w * q2.y - q1.x * q2.z + q1.y * q2.w + q1.z * q2.x;
  newQ.z = q1.w * q2.z + q1.x * q2.y - q1.y * q2.x + q1.z * q2.w;

  return  newQ;
}

-(void)updateCameraFromMotion:(CMDeviceMotion *)deviceMotion {

  CMAttitude  * attitude    = deviceMotion.attitude;
  CMQuaternion  quaternion  = attitude.quaternion;
  CC3Vector4    camQuaternion;
  camQuaternion.w =  quaternion.w;
  camQuaternion.x = -quaternion.x;
  camQuaternion.y = -quaternion.z;
  camQuaternion.z =  quaternion.y;
  camQuaternion   = [self multiplyQuaternion:camQuaternion onAxis:CC3Vector4Make(1, 0, 0, 0) byDegress:90];
  self.activeCamera.quaternion = camQuaternion;  

}

请注意,开始时相机的 forwardDirection 很重要,我将其设置为 (1,0,0)

于 2012-07-27T11:42:24.880 回答