使用四元数旋转对象

时间:2014-10-06 08:18:17

标签: ios rotation transform quaternions

我尝试使用平底锅旋转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;

我将水平和垂直运动分开。原点变量是三维视图中物体的原始位置。问题是有时物体会产生偏航角度旋转并且旋转变得混乱,有时物体本身!当我在屏幕上混乱地制作平底锅时会出现这种情况。我试图使运动正常化,但这对我没有帮助。有人能告诉我我做错了什么。

1 个答案:

答案 0 :(得分: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保持当前对象旋转。

我的摘要:要乘以'旋转',请始终使用四元数,然后将其转换为旋转矩阵。

相关问题