Pierro787 Pierro787 - 1 year ago 74
iOS Question

Swift - SpriteKit : Make sprites reacting to eachothers if added with different "addchild" parents

I've added several sprite (SKSpriteNode) in my Scene like this:

let NPuzzle_Texture = SKTexture(imageNamed: "SKTexture.png")
NPuzzle0 = SKSpriteNode(texture: NPuzzle_Texture)
NPuzzle1 = SKSpriteNode(texture: NPuzzle_Texture)
NPuzzle2 = SKSpriteNode(texture: NPuzzle_Texture)
NPuzzle0.position = CGPoint (x: 100, y:125)
NPuzzle0.position = CGPoint (x: 300, y:125)
NPuzzle0.position = CGPoint (x: 500, y:125)

I've also added several sprites in a different texture:

let Grey_Back = SKTexture(imageNamed: "Grey_Back.png")
grey_back = SKSpriteNode(texture: Grey_back)
grey_back.position = CGPoint (x: 1024, y:125)
grey_back.alpha = 0.5

Now I add new sprites (SKSpriteNode) to precedent grey_back like this:


When I try to see if positions of new_sprite intersects with NPuzzle sprites, nothing is happening. But if the new_sprite are added to the scene with:


it works. In fact it doesn't work if the sprites have been added with differents parents (background and grey_back). What I don't understand is grey_back is the child of background, so, it should work. Why it doesn't ?

Here is an example of the code to check if sprites intersects eachothers:

switch selectedNode.name {

case "new_sprite0":
if selectedNode.frame.intersects(NPuzzle0.frame) && (selectedNode.angle == 0) {

Thanks !

Answer Source
switch selectedNode.name {
let framePoint = CGPointMake(selectedNode.frame.origin.x, selectedNode.frame.origin.y)
let translatedPoint = selectedNode.parent!.convertPoint(framePoint, toNode:NPuzzle0.parent!)
let translatedFrame = CGRectMake(translatedPoint.x, translatedPoint.y, selectedNode.frame.size.width, selectedNode.frame.size.height)
if translatedFrame.intersects(NPuzzle0.frame) && (selectedNode.zRotation == 0) 

Obviously, because frames are relative to parents, the node MUST be added to the scene. You can see I also used a forced unwrap for parent...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download