我在GLKit中有一个跟随用户手指的纹理。我计算弧度以在两点之间使用arctan绘制角度。
这里的部分技巧是保持对象在手指下居中。所以我已经介绍了锚点的想法,以便可以相对于它们的起点或中心绘制事物。我的目标是将精灵移动到位,然后旋转。我的渲染器中有以下代码。
// lets adjust for our location based on our anchor point.
GLKVector2 adjustment = GLKVector2Make(self.spriteSize.width * self.anchorPoint.x,
self.spriteSize.height * self.anchorPoint.y);
GLKVector2 adjustedPosition = GLKVector2Subtract(self.position, adjustment);
GLKMatrix4 modelMatrix = GLKMatrix4Multiply(GLKMatrix4MakeTranslation(adjustedPosition.x, adjustedPosition.y, 1.0), GLKMatrix4MakeScale(adjustedScale.x, adjustedScale.y, 1));
modelMatrix = GLKMatrix4Rotate(modelMatrix, self.rotation, 0, 0, 1);
effect.transform.modelviewMatrix = modelMatrix;
effect.transform.projectionMatrix = scene.projection;
另一个注意事项是我的精灵在纹理别名上。如果我取出我的旋转,我的精灵正确地在我的手指下方画中心。我的项目矩阵是GLKMatrix4MakeOrtho(0,CGRectGetWidth(self.frame),CGRectGetHeight(self.frame),0,1,-1);所以它匹配UIkit及其嵌入的视图。
答案 0 :(得分:2)
我最后需要添加一些数学来计算旋转之前的额外偏移量。
// lets adjust for our location based on our anchor point.
GLKVector2 adjustment = GLKVector2Make(self.spriteSize.width * self.anchorPoint.x,
self.spriteSize.height * self.anchorPoint.y);
// we need to further adjust based on our so we can calucate the adjust based on our anchor point in our image.
GLKVector2 angleAdjustment;
angleAdjustment.x = adjustment.x * cos(self.rotation) - adjustment.y * sin(self.rotation);
angleAdjustment.y = adjustment.x * sin(self.rotation) + adjustment.y * cos(self.rotation);
// now create our real position.
GLKVector2 adjustedPosition = GLKVector2Subtract(self.position, angleAdjustment);
GLKMatrix4 modelMatrix = GLKMatrix4Multiply(GLKMatrix4MakeTranslation(adjustedPosition.x, adjustedPosition.y, 1.0), GLKMatrix4MakeScale(adjustedScale.x, adjustedScale.y, 1));
modelMatrix = GLKMatrix4Rotate(modelMatrix, self.rotation, 0, 0, 1);
这将根据我们想要旋转的图像中的位置创建一个额外的调整,然后根据它进行转换。这就像一个魅力..
答案 1 :(得分:0)
我使用类似的代码围绕其中心旋转精灵
首先将它移动到该位置,然后旋转它,然后将它移回半精灵
- (GLKMatrix4) modelMatrix {
GLKMatrix4 modelMatrix = GLKMatrix4Identity;
float radians = GLKMathDegreesToRadians(self.rotation);
modelMatrix = GLKMatrix4Multiply(
GLKMatrix4Translate(modelMatrix, self.position.x , self.position.y , 0),
GLKMatrix4MakeRotation(radians, 0, 0, 1));
modelMatrix = GLKMatrix4Translate(modelMatrix, -self.contentSize.height/2, -self.contentSize.width/2 , 0);
return modelMatrix;
}