2
votes

I have a sprite added to a layer. I am having a lot of problems when I transform the layer. As far as I know a layer has its center (anchorPoint) on the bottom left corner and a layer has it in the middle (right?) - I am not totally sure about that.

On the figures below, I represent a CClayer in pink and a CCSprite in purple. See where I think the centers are.

When I add a sprite to a layer, I think Cocos will do like in A, but I want it like in B. How do I do that? Another possibility is C, that I think is better, but that would involve moving the anchorPoint of the layer to the middle and put the sprite there... I don't a have a clue on how to do that.

enter image description here

3

3 Answers

3
votes

Change anchor point of CCSprite.

CCSprite *sprite = [CCSprite spriteWithFile:@"sprite.png"];

//For case A
sprite.anchorPoint = ccp(0.0f,0.0f); 
sprite.position = ccp(0.0f,0.0f);

//For case B
sprite.anchorPoint = ccp(0.5f,0.5f); 
sprite.position = ccp(0.0f,0.0f);


//For case c
sprite.position = ccp(ScreenWidth/2.0f, ScreenHeight/2.0f);
sprite.anchorPoint = ccp(0.5f,0.5f);
0
votes

Anchor point is relatieve coordinate. (0.f, 0.f) is left-bottom corner of the node, (1.f, 1.f) is right-top corner. All transformations are make relatieve to the anchor point. Positioning is also transform. It means that in case of anchor point (0.5f, 0.5f) all positioning and other transforms will be applied relatieve to the center of the node. If you want to place your sprite to the left-bottom corner of your layer, you can simply set it's anchor point to (0.f, 0.f) and set position (0.f, 0.f). It means that left-bottom corner of your sprite will be placed to the (0.f, 0.f) coordinate of your parent layer.

[sprite setAnchorPoint:ccp(0.f, 0.f)];
[sprite setPosition:ccp(0.f, 0.f)];
[layer addChild:sprite];
-1
votes

When I add a sprite to a layer, I think Cocos will do like in A, but I want it like in B.

Don't try to guess behaviour. Add sprite to the layer and see what happens.

Also, CCNode and all its subclasses, including CCSprite, have position property, which represents node's position relative to its parent's origin.