2015-07-11 67 views
1

我有一個看起來像這樣的精靈。在三角形精靈上創建SKPhysicsBody

enter image description here

我將如何創造這個精靈的SKPhysicsBody?我需要它,以便SKPhysicsBody既可以是三角形,也可以是精靈長邊上的一條邊。這是我到目前爲止。精靈,叫rightEnemy,有

CGPointMake(0.5, 0.5); 
rightEnemy.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(rightEnemy.position.x + width, rightEnemy.position.y) toPoint:CGPointMake(rightEnemy.position.x, rightEnemy.position.y + height)]; 

錨點這將創建一個物理體,但由於某種原因,它沒有連接到精靈。

物理主體所連接的精靈通過更新方法不斷移動。 y值總是在變化。

回答

1

您可能想嘗試從紋理中創建物理身體。

rightEnemy.physicsBody = [SKPhysicsBody bodyWithTexture:rightEnemy.texture size:rightEnemy.size]; 

你也可以這樣做來驗證物理設置是否正確。

self.scene.view.showsPhysics = YES; 

編輯

對於iOS 7

未經測試,但我會想象bodyWithEdgeFromPoint:需要在精靈的座標系。你可以試試這個「應該」從你的精靈的左下角到右上角畫一條線。

rightEnemy.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(-rightEnemy.size.width/2, -rightEnemy.size.height/2) toPoint:CGPointMake(rightEnemy.size.width/2, rightEnemy.size.height/3)]; 

希望有幫助。

+0

是否有iOS 7替代? – PoKoBros

+0

@PoKoBros我更新了我的答案我認爲問題在於你並不是在精靈座標系中。你也可以嘗試bodyWithPolygonFromPath:希望有幫助。 –

1

您可以創建一個三角形物理體是這樣的:

CGMutablePathRef trianglePath = CGPathCreateMutable(); 
CGPathMoveToPoint(trianglePath, nil, -myNode.size.width/2, myNode.size.height/2); 
CGPathAddLineToPoint(trianglePath, nil, myNode.size.width/2, -myNode.size.height/2); 
CGPathAddLineToPoint(trianglePath, nil, -myNode.size.width/2, -myNode.size.height/2); 
CGPathAddLineToPoint(trianglePath, nil, -myNode.size.width/2, myNode.size.height/2); 
myNode.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:trianglePath]; 

CGPathRelease(trianglePath); 

上面創建了一個45度的右三角面對。

2

以下是答案的Swift版本。

var trianglePath:CGMutablePathRef = CGPathCreateMutable() 
    CGPathMoveToPoint(trianglePath, nil, -self.size.width/2, self.size.height/2) 
    CGPathAddLineToPoint(trianglePath, nil, self.size.width/2, -self.size.height/2) 
    CGPathAddLineToPoint(trianglePath, nil, -self.size.width/2, -self.size.height/2) 
    CGPathAddLineToPoint(trianglePath, nil, -self.size.width/2, self.size.height/2) 

    self.physicsBody? = SKPhysicsBody(polygonFromPath: trianglePath)