Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprite-Kit : Sprite z-Order

Tags:

sprite-kit

How to Change Sprite's z-Order in Sprite-Kit?

Cocos2d Code:

[parentNode addChild:sprite1 z:3];
[parentNode addChild:sprite2 z:2];
[parentNode addChild:sprite3 z:1];

I tried below code in Sprite-Kit..but its not changing z-order

[parentNode insertChild:sprite1 atIndex:3];
[parentNode insertChild:sprite2 atIndex:2];
like image 398
iCodeXcode Avatar asked Mar 10 '14 15:03

iCodeXcode


2 Answers

For draw order use the zPosition property of a node:

zPosition The height of the node relative to its parent.

The default value is 0.0. The positive z axis is projected toward the viewer so that nodes with larger z values are closer to the viewer. When a node tree is rendered, the height of each node (in absolute coordinates) is calculated and then all nodes in the tree are rendered from smallest z value to largest z value. If multiple nodes share the same z position, those nodes are sorted so that parent nodes are drawn before their children, and siblings are rendered in the order that they appear in their parent’s children array. Hit-testing is processed in the opposite order.

The SKView class’s ignoresSiblingOrder property controls whether node sorting is enabled for nodes at the same z position.

You can also use insertChild:atIndex: to affect z order but keep in mind that index is the index of the object in the array, not it's zPosition (ie atIndex parameter is not the same as the z parameter in cocos2d, in fact it's the inverse). Nodes added at a lower index will be drawn before nodes at a higher index.

Also note that you can't insert nodes at an index out of bounds. From the NSMutableArray docs:

[..] you cannot insert an object at an index greater than the current count of an array. For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableArray raises an exception.

like image 163
LearnCocos2D Avatar answered Sep 22 '22 09:09

LearnCocos2D


In Swift you can do:

sprite.zPosition = 1

Usually the zOrder is , just to make an example:

-1 (put it to the back)

0 (in the middle, it's also the default value)

1 (put it in front of all)

When all your objects have the same zPosition (for example the default 0.0) and they are added to the same parent node, the order they appear is estabilished by the "addChild" order in your code: the last is in front of all.

like image 34
Alessandro Ornano Avatar answered Sep 23 '22 09:09

Alessandro Ornano