作为一个单元旋转时重叠的SpriteNodes

时间:2017-07-15 20:29:17

标签: ios swift swift3 sprite-kit skspritenode

使用Swift 3和Spritekit开发应用程序时遇到了问题。为了检测碰撞,我制作了四个独立的三角形组成一个正方形。当我将这些三角形作为一个单位旋转时,它们重叠并且在旋转期间不保持正方形的形状(它们彼此重叠),但是一旦旋转完成就会恢复正常。

这是我用于轮换的代码:

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

请随时向我询问您需要查看的任何其他代码,任何输入都有帮助。此外,我无法在行动中得到重叠的问题,所以提前抱歉,但我会尽力去做。

1 个答案:

答案 0 :(得分: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))