2012-07-20 122 views
3

我想從cocos3d添加3D對象作爲iPhone應用中增強現實的相機覆蓋。我有一些模型的CC3Scene。我創建了MotionManager捕獲以獲取有關設備攝像頭方向的信息,然後在 - (void)update:(ccTime)dt我試圖更新cocos3d現場攝像頭的位置(場景的上方向是Z軸) :Cocos3d和增強現實

-(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(俯仰,滾轉,偏航),因爲旋轉的茯苓中的順序(與我的當前軸)不匹配一個在裝置中。但是我的代碼也不能正確工作。手動旋轉相機時出現錯誤,我不知道該如何旋轉才能使其正確(我嘗試了幾乎所有的順序和軸組合)。

所以問題是如何匹配科科斯的相機旋轉和設備的一個?我錯過了什麼嗎?或者你可以提供代碼或教程項目與這些主題?我明白這是一個相當簡單的問題,因爲只有三角函數,但我已經打定了要做的事情。

謝謝!

回答

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)

完成