1

我在 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 和它嵌入的视图。

4

2 回答 2

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);

这将根据我们想要旋转的图像中的位置创建额外的调整,然后基于该位置进行转换。这就像一个魅力..

于 2012-02-24T20:15:15.887 回答
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;
}
于 2013-06-03T00:16:29.117 回答