Pierro787 Pierro787 - 5 months ago 25
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)
background.addChild(NPuzzle0)
background.addChild(NPuzzle1)
background.addChild(NPuzzle2)


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
background.addChild(grey_back)


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

grey_back.addChild(new_sprite1)
grey_back.addChild(new_sprite2)
grey_back.addChild(new_sprite3)


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:

background.addChild(new_sprite0)
background.addChild(new_sprite1)
background.addChild(new_sprite2)


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
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) 
{
    print("ok")
}

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...

Comments