Reputation:
I've encountered an issue when developing my application using Swift 3 and Spritekit. I have made four separate triangles that make up a square for the sake of detecting collision. When I go to rotate these triangles as one unit they overlap and do not hold the shape of a square(they overlap each other) during the rotation but then go back to normal once the rotation is complete.
This is the code I used for the rotation:
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))
}
}
}
Below is a picture of my square made up of four separate triangles
Please feel free to ask me for any other code you need to see, any input helps. Also I couldn't get the overlapping issue in action so sorry in advance but I will try my best to get it.
Upvotes: 4
Views: 110
Reputation: 21976
The problem is that you're rotating the single triangles, that get rotated according to their own coordinate system. Imagine that each triangle is pinned in the center and it's rotated around it. Clearly the triangles will overlap. You should rotate them around a unique point. In your case, the simplest way to do that is to add them to the same parent node, and then rotate the parent:
// 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))
Upvotes: 7