2014-10-06 79 views
0

我想用平底鍋旋轉3d view中的對象。有2個旋轉軸:對象Y軸和全局固定X軸。在y軸周圍,我簡單地使用方法CATransform3DRotate生成的旋轉矩陣旋轉,並圍繞固定的x軸使用四元數。 在這裏,我的一些代碼至極演示行爲:用四元數旋轉對象

UITouch* touch = [touches anyObject]; 
CGPoint location = [touch locationInView: viewController.view]; 
CGPoint lastLoc = [touch previousLocationInView: viewController.view]; 
CGPoint diff  = CGPointMake(lastLoc.x - location.x, lastLoc.y - location.y); 

float rotX = 1 * DEGREES_TO_RADIANS(diff.y/4.0); 
float rotY = -1 * DEGREES_TO_RADIANS(diff.x/4.0); 

CATransform3D m = glView.modelTransform; 
if(fabs(diff.y) > fabs(diff.x) * 5.0) { //up-down 
    Vector3D xAxis = {1.0, 0.0, 0.0}; 
    Vector4D quaternion = [self makeQuaternionFromAxis: xAxis andAngle:rotX]; 
    Vector4D currentQuaterion = [self makeQuaternionFromRotationMatrix: m]; 
    quaternion = [self multiplyQuaternion:currentQuaterion buAnother:quaternion]; 
     m = [self makeRo 
    tationMatrixFromQuaternion:quaternion]; 
     m = CATransform3DConcat(m, origin); 
    } 
else {         //right-left 
    Vector3D yAxis = {0.0, 1.0, 0.0}; 
    m = CATransform3DRotate(m, rotY, yAxis.x, yAxis.y,yAxis.z); 
} 
glView.modelTransform = m; 

我單獨的水平和垂直移動。原始變量是3D視圖中對象的原始位置。問題是有時對象會獲得偏航角度旋轉,並且旋轉會變得混亂,有時候對象本身也會變得混亂!當我混亂地在屏幕上製作平底鍋時會出現這種情況。我試圖規範運動,但這沒有幫助我。有人能告訴我我做錯了什麼嗎?

+0

已解決此問題。 – Demonoid67 2014-10-06 10:50:43

回答

0

固定碼是這樣的:

Vector4D quaternion; 
if(fabs(diff.y) > fabs(diff.x)) { //up-down 
    Vector3D xAxis = {1.0, 0.0, 0.0}; 
    quaternion = [self makeQuaternionFromAxis: xAxis andAngle:rotX]; 
    quaternion = [self multiplyQuaternion:quaternion buAnother:currentQuaterion]; 
    } 
else {         //right-left 
    Vector3D yAxis = {0.0, 1.0, 0.0}; 
    quaternion = [self makeQuaternionFromRotationMatrix:CATransform3DMakeRotation(rotY, yAxis.x, yAxis.y,yAxis.z); 
    quaternion = [self multiplyQuaternion:quaternion buAnother:currentQuaterion] 
} 
currentQuaterion = quaternion; 
glView.modelTransform = CATransform3DConcat([self makeRotationMatrixFromQuaternion:quaternion],perspective); 

currentQuaternion保持當前對象的旋轉。

我的概要:乘以'旋轉'總是使用四元數,而不是將tham轉換爲旋轉矩陣。