'Switch between parents - SpriteKit
In my game I have two SKNodes called "Center" rotating.
I have several objects as the child of Center (the SKNode). I did this so I could let these objects orbit around Center. Although at certain points I want to switch to other SKNodes - "Center2". In this I have named one of the objects "Onject", which switched between parents I need to attach and detach at certain points in my game. I have tried, after doing self.addChild(Object) then doing Center.addChild(Object). My game crashed.
How do I switch between parents for objects?
Solution 1:[1]
there is a method called move(toParent:SKNode) to do exactly what you want, it will also fix the coordinates for you.
Solution 2:[2]
If you call self.addChild(Object) and then Center.addChild(Object) your game will crash, because the object will then have two parents. You cant add the object twice as a child for different nodes.
If you want to switch the parent, you have to remove it first from its parent, so the flow will be as follows:
self.addChild(Object)(then just perform your game logic)
once its time to switch the parent, follow these steps:
Object.removeFromParent()Center.addChild(Object)
Then your object has a new parent
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Knight0fDragon |
| Solution 2 | Luke |
