2017-07-15 9 views
4

我在使用Swift 3和Spritekit開發我的應用程序時遇到了一個問題。爲了檢測碰撞,我製作了四個獨立的三角形組成正方形。當我將這些三角形作爲一個單元旋轉時,它們重疊並且在旋轉過程中不保持正方形的形狀(它們彼此重疊),但一旦旋轉完成後就會恢復正常。作爲一個單元旋轉時重疊SpriteNodes

這是我用於旋轉代碼:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for touch in touches{ 
     let location = touch.location(in: self) 

     if location.x < 0 { 
      blueTriLeft.run(SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 0.2)) 
      redTriLeft.run(SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 0.2)) 
      yellowTriLeft.run(SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 0.2)) 
      greenTriLeft.run(SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 0.2)) 

     } else if location.x > 0 { 
      blueTriRight.run(SKAction.rotate(byAngle: CGFloat(-M_PI_2), duration: 0.2)) 
      redTriRight.run(SKAction.rotate(byAngle: CGFloat(-M_PI_2), duration: 0.2)) 
      yellowTriRight.run(SKAction.rotate(byAngle: CGFloat(-M_PI_2), duration: 0.2)) 
      greenTriRight.run(SKAction.rotate(byAngle: CGFloat(-M_PI_2), duration: 0.2)) 
     } 
    } 
} 

下面是我的廣場由四個單獨的三角形

square

請隨時問我要照片你需要看到的任何其他代碼,任何輸入都有幫助。此外,我無法事先得到重疊問題,所以我會盡我所能去解決。

回答

8

問題是,你正在旋轉單個三角形,根據他們自己的座標系得到旋轉。想象一下,每個三角形都固定在中心,並圍繞它旋轉。顯然三角形將重疊。你應該圍繞一個獨特的點旋轉它們。在你的情況下,最簡單的方法是將它們添加到同一父節點,然後旋轉父代:

// This is the configuration to do in sceneDidLoad 
let node = SKNode() 
node.addChild(blueTriLeft) 
node.addChild(redTriLeft) 
node.addChild(yellowTriLeft) 
node.addChild(greenTriLeft) 
scene.addChild(node) 

// Inside touchesBegan(_:, with:) 
node.run(SKAction.rotate(byAngle: CGFloat(-M_PI_2), duration: 0.2)) 
+0

我必須在觸摸開始函數或類中聲明嗎? –

+0

blueTriLeft = self.childNode(withName:「blueTriLeft」)as! SKSpriteNode –

+0

^^^^^^這將抵消上述解決方案 –