问题
I am stuck with the problem of layer hierarchy in cocos2d.
I have a character with sprites for its body parts. The parent sprite of the body is the torso. Then I have arms and head that are the children of it, then elbows and hands are children of the arms. It works very well so far: I turn the elbow and the hand is turning with it, just like on a real puppet.
The problem is when I want to make it wave, the hands get behind the head since head has a higher z-order than arms (which are parents of the hands).
So, I added another hand as a child of torso and turn its opacity ON and OFF depending whether I need the hand above or behind the head. However, another hand is not the child of the arm, it is a child of the torso and doesn't rotate whenever the arm is rotating. So, I need to position it manually each frame.
So my question is: Is it possible to parent the sprite of one node to inherit its translation, but draw it above the other specified sprite? (like above another sibling of its parent)
Changing z-order of arms and head is out of question since the animation is exported from another program which doesn't support these parameters.
Thank you!
回答1:
How is the "animation exported" from another program? I believe that this would be the issue. If I were to do it, I would use the Z layer. Better yet, look at Sprite Atlases for creating your animation.
I think you are doing way too much to create the animation. With an Atlas, you would create the animation for the figure putting it's hands up and waving them. and then just call the animation on the sprite atlas.
回答2:
I solved the.same problem in my application by putting an extra invisible torso sprite to the model. in thos case you can bind one arm and the head to invisible torso and the other one to the second torso
回答3:
I think I found the solution to my problem. It is a vertexZ property of the node.
/** The real openGL Z vertex.
Differences between openGL Z vertex and cocos2d Z order:
- OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children
- OpenGL Z might require to set 2D projection
- cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0
@warning: Use it at your own risk since it might break the cocos2d parent-children z order
@since v0.8
*/
@property (nonatomic,readwrite) float vertexZ;
This article describes how to use it
回答4:
Also make sure you initi the EAGLView with the depth enabled
EAGLView *glView = [EAGLView viewWithFrame: [window bounds]
pixelFormat: kEAGLColorFormatRGBA8
depthFormat: GL_DEPTH_COMPONENT16_OES];
来源:https://stackoverflow.com/questions/7245769/cocos2d-layer-hierarchy-and-draw-order