I am currently attempting to create a game that will auto generate platforms on the scene when a platform leaves the scene.
I have created 5 SKSpriteNodes and added them as children to a Platform SKNode.
I then move them accross the screen with platformGroupNode.position.x--
inside my update function
However, I would like to detect when one of the children leaves the screen, so that I can generate a new platform.
I have tried the below, but it only seem to give me a position for that child inside the parent node
for child in shipGroupNode.children {
println(child.position.x)
}
Is there a better way to group Sprite Nodes to allow me to view their individual properties in relation to the scene and control there are a group?
Code ------------
mport SpriteKit
// Globals
let platformGroupNode = SKNode()
var platformX:CGFloat = 200
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
platformGroupNode.position = CGPoint(x: 0, y: 0)
addChild(platformGroupNode)
// Add platforms
addPlatform(platformX)
// Add platforms
for i in 1...4 {
addPlatform(platformX)
//println(platformX)
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
platformGroupNode.position.x--
for child in platformGroupNode.children {
println(child.position.x)
println(convertPointToView(CGPoint(x: child.position.x, y: child.position.y)))
}
}
func addPlatform(platformx:CGFloat) {
let platform = SKSpriteNode(imageNamed:"Spaceship")
platform.xScale = 0.5
platform.yScale = 0.5
platform.position = CGPoint(x: platformx, y: self.size.height/2)
platformX = platformx + 200
platformGroupNode.addChild(platform)
}
}
You can use the
intersectsNode
method onSKScene
to check whether the child nodes are visible;intersectsNode
will returntrue
whilst the children are visible.An alternative to removing and then creating a new platform would be to reposition the platform that just moved offscreen, so it will move back onscreen. For example: if scrolling from right to left, when a platform moves off the left edge it will be repositioned on the right. This has the advantage of only needing to create a few platforms at the beginning.
For this to work correctly it's essential that your
SKScene
'ssize
is equal to itsSKView
size. For information on this have a look at SpriteKit Coordinates differ between iPad and iPhone