Missing z-axis rotation for transforming between two vectors
Posted
by
Steve Baughman
on Game Development
See other posts from Game Development
or by Steve Baughman
Published on 2012-05-23T15:58:02Z
Indexed on
2012/06/01
22:51 UTC
Read the original article
Hit count: 357
I'm trying to rotate a cube so that it's facing up, but am getting hung up on the final implementation details. It now reliably will rotate the x,y axis to the correct side, but the z-axis is never rotating (See photos of before and after rotation). When I'm using the code below I always get '0' for my rotationVector.z. What am I missing here?
// Define lookAt vector
lookAtVector = GLKVector3Make(0,0,1);
// Define axes vectors
axes[0] = GLKVector3Make(0,0,1);
axes[1] = GLKVector3Make(-1,0,0);
axes[2] = GLKVector3Make(0,1,0);
axes[3] = GLKVector3Make(1,0,0);
axes[4] = GLKVector3Make(0,-1,0);
axes[5] = GLKVector3Make(0,0,-1);
CGFloat highest_dot = -1.0;
GLKVector3 closest_axis;
for(int i = 0; i < 6; i++) {
// multiply cube's axes by existing matrix
GLKVector3 axis = GLKMatrix4MultiplyVector3(matrix, axes[i]);
CGFloat dot = GLKVector3DotProduct(axis, lookAtVector);
if(dot > highest_dot) {
closest_axis = axis;
highest_dot = dot;
}
}
GLKVector3 rotationVector = GLKVector3CrossProduct(closest_axis, lookAtVector);
// Get angle between vectors
CGFloat angle = atan2(GLKVector3Length(rotationVector), GLKVector3DotProduct(closest_axis, lookAtVector));
// normalize the rotation vector
rotationVector = GLKVector3Normalize(rotationVector);
// Create transform
CATransform3D rotationTransform = CATransform3DMakeRotation(angle, rotationVector.x, rotationVector.y, rotationVector.z);
// add rotation transform to existing transformation
baseTransform = CATransform3DConcat(baseTransform, rotationTransform);
return baseTransform;
Before 3d Rotation
After 3d Rotation
© Game Development or respective owner