Switch between parents - SpriteKit - swift

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?

there is a method called move(toParent:SKNode) to do exactly what you want, it will also fix the coordinates for you.

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

Related

Why does parenting an object in the hierarchy produce different results then parenting via script?

Parenting GIF (for visual)
When parenting an object using the hierarchy you click and drag that object and place it into another game object.
When parenting an object using a script, it looks something like this
myObject.transform.SetParent(parentObject, false);
Now, if you watch the GIF you will see that the two different methods of parenting produce different results for the child objects transform values. The resulting position and scale are different for the child object depending on which approach to object parenting is used.
How do you get the same results produced when parenting in the hierarchy via click and drag, when parenting by script?
EDIT: Forgot to add that when watching the gif, you can see the click and drag parenting first and watch the transform values change. I then control Z to undo the change, click into the scene view, and execute a button press that sets the parent of the 'blue' game object to 'myObject'. Note, you will see the transform values don't change when parenting is done via the latter method.
If we check Unity's API documentation for the SetParent() method we can better understand how this method works. In my case I was using the method that used two parameters:
parent:
The parent Transform to use
worldPositionStays:
When false the object keeps its local orientation rather than its global
For my question, there are two simple solutions:
Set the worldPositionStays parameter to true so that the parent-relative position, scale and rotation are modified such that the child object keeps the same world space position, rotation and scale as before, or
Use the SetParent() method with only the parent parameter, effectively yields the exact same result as setting worldPositionStays to true.

Creating a class to run a single action on multiple sprites

I'm trying to rotate numerous sprites (about 48 different ones) around an arbitrary point (using this article: http://indiedevstories.com/2012/08/14/custom-cocos2d-action-rotating-sprite-around-arbitrary-point/ ) and I managed to create the custom category for it, but it only works on a single sprite. I've looked around on the site and tried to use runAction:[action copy] but it makes the copies rotating points crazy numbers for some reason. Then I tried to create a method for the actions and just call the method, but I keep getting errors for that as well. I've tried so many different solutions but no luck.
So my question is, is there a way I can create another class that holds all of my sprites, and then run a single method to run an action on all of the sprites of the class?
Assuming you have an array called spriteArray containing all sprites you wish to rotate, it's as simple as:
for(CCSprite *sprite in spriteArray)
{
CCRotateAroundBy *rotateAround = [CCRotateAroundBy actionWithDuration:1.0 angle:90 rotationPoint:screenCenter];
[sprite runAction:rotateAround];
}

change parent of a CCSprite in cocos2D

I'm kind of new in cocos2Dm and i'm facing a problem that i can't solve
So far I have 2 sprites (let's call them tables) in the layer , that is touchable, one of them has added other sprites, that I wanna move from one table to another one, i'm recognizing the objets that I touch, & moving them around, My problem is that I can't change the parent to be the other table, I tried to remove the object from parent in different ways & add the no the new parent, but it doesn't seem to work, the object is duplicated cause it's not being removed, I even tried to remove them when I touch it.
I'm storing the objects in _objectsToDrag & calling this function in touchbegan:
- (void) lookForObjectWithTouchLocation:(CGPoint)touchLocation
{
for (RICCObject *object in _objectsToDrag) {
if (CGRectContainsPoint(object.boundingBox, touchLocation)) {
_selectedObject = object;
}
}
if (_selectedObject) {
[self objectSelectedWithLocation:touchLocation];
}
}
And then using _selectedObject to move it around, is this the problem? should I use aributes instead local objects in an array?
Any help is welcome
Thank you in advance
To move an instance of a class that derives from CCNode (like CCSprite, CCLabelTTF etc) from one parent node to another, follow this process:
// get yourNode in whatever way fits your implementation ...
CCNode* nodeToMove = yourNode;
// not cleaning up leaves actions running
[nodeToMove removeFromParentAndCleanup:NO];
// add the removed node to its new parent node
[newParentNode addChild:nodeToMove];
This process works regardless of how or where else you store the nodes.
Note that if you see nodes being duplicated, you either create a new node without removing the old node or you have two nodes to begin with. In cocos2d, a CCNode can only have one parent and trying to add a node that already has a parent to another node will prompt you with an error message. If you experience duplicated nodes respectively removing a node from its parent still keeps it on screen try to find the cause for that first. This is something that doesn't happen under normal circumstances, except when you actually create multiple versions of the same node.

Box2D and wrapping worlds

I really stuck at implementing wrapping world with Box2D. I want to create game object appearing from left when it hides to the right and vice versa and the same for top-down.
My idea is to use object wich contains NSArray with 9 elements for superposition matrix (it's a quantum state when object exists at different locations at the same time, isn't it?).
Every element must contain the body. It covers all situations and has a more clear logic for me. For example, if my object doesn't touch any edges it holds only one "center" body (4th element). If it touches right edge i add "left-warped" body to 3rd element.
The main problem is creating body without adding to the world. First i must just add it to the array and then safely proccess adding outside of
world->Step();
For example… In collision logic (pseudocode)
[self.bodies addObjectAtIndex:index] = [self masterBody];
where
-(b2Body*)masterBody;
returns a template (master copy) for object body. But i can't write this method because there is only one
world->CreateBody(&bodyDef);
method and i must use it to create fixtures.
I can create separately only definition of the body, but full creation (with fixtures) can't be made without adding it to the world. But adding to the world msut be processed outside physics step.
Any ideas? Use separate world for storing template bodies of every game object?

Creating pointer Attributes in cocos2d iPhone

I am working on a game. There are balls that fall from the top of the screen, and the player has to catch them, as the are caught they stack ontop of one another. I have a method that creates each new ball and adds it to an Array that i use to move the sprites. Problem is that the after they collide I need them to stop moving, since the array is called on to move them they all move. And if i try to make them stop they all stop. So I was hoping to create a pointer attribute if ther is such a think, for example "sprite.position" I need a new attribute that i can check like a boolean. I was hoping to create a attribute like sprite.hasCollided and if it returns YES then the ball should no longer move. Is this possible or is there a better way to do it?
Thanks
Tanner
I would suggest you create a ball object. And add the boolean as as part of the object.
CCNodes (and, by inheritence, CCSprites) have a userData property, which is a void*. You can use this to relate a custom object to a cocos2d object. Keep in mind if you use the userData option, you will, in most cases, need to allocate any memory when you create/assign the sprite, and release it when you are done.
int* myInt = (int*)malloc(sizeof(int));
*myInt = 0;
sprite.userData = myInt;
//some time later, when you are done with the sprite
free(sprite.userData);
As an improvement on the userData property, you can do what xuanweng suggests and create a ball object containing various game-related properties for the balls, and assign an instance of this to each of your ball CCSprites using the method above.