2012-02-23 58 views
1

我有一個在GLKit中跟隨用戶手指的紋理。我計算弧度以在兩點之間使用arctan繪製角度。如何使用GLKit在精靈的中心旋轉圖集

這裏的訣竅的一部分是保持對象居中供應不足的手指。所以我介紹了一個定位點的概念,以便可以相對於其原點或中心繪製事物。我的目標是將精靈移動到位,然後旋轉。我在渲染器中有以下代碼。

// 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和它嵌入的視圖。

回答

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

這將根據我們想旋轉的圖像中的位置創建一個額外的調整,然後基於此進行轉換。這就像一個魅力..

0

還有就是我用來圍繞其中心

首先旋轉精靈類似的代碼,你將它移動到的位置,那麼你轉動它,那麼你將其移回halfsprite

- (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; 
}