There’s something in cocos2d which is super easy to understand, but that most people seem to have problems with it at first : Anchor Points. Every class derived from CCNode (Ultimate cocos2d class) will have a anchorPoint property. When determining where to draw the object (sprite, layer, whatever), cocos2d will combine both properties position and anchorPoint. Also, when rotating an object, cocos2d will rotate it around its anchorPoint, as if a pin were placed on that very spot. PositioningAs a first example, this sprite has an anchorPoint of ccp(0,0) and a position of ccp(0,0). This rectangle sprite will be placed at the bottom left corner of its parent, the layer. CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"]; sprite.position=ccp(0,0); sprite.anchorPoint=ccp(0,0); [self addChild:sprite]; // 原点默认位置是左下角, anchorPoint就是原点位置, 默认是ccp(0,0) // anchorPoint的默认位置Layer的是左下, 而其他的node是中点
CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"]; sprite.position=ccp(0,0); sprite.anchorPoint=ccp(-1,-1); [self addChild:sprite];
As a final example, to better understand the combination of position and anchorPoint, I’ll show you different lines of code that give exactly the same result as the first image. That piece of code will combine both position and anchorPoint, and show you how to use the contentSize property. CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"]; sprite.anchorPoint=ccp(1,1); sprite.position=ccp(sprite.contentSize.width , sprite.contentSize.height); [self addChild:sprite]; Using this snippet, we place the anchorPoint at ccp(1,1), which places it 1 * width to the right and 1 * height over. If we kept position at ccp(0,0), the sprite would be outside the screen, to the bottom left of it. By placing the sprite at a position equal to ccp(1 * width, 1* height), it returns to the origin, at the bottom left corner. RotationWhen rotating, we need to be careful with anchorPoint, as it can give us some very weird results, more so when using irregular anchor points such as ccp(0,0). By default, the anchorPoint is set to ccp(0.5f,0.5f), which is the middle of the sprite on both X and Y axes (remember that anchorPoint is a relative value to the size of the sprite). Using ccp(0.5f,0.5f) as an anchorPoint will give the simplest rotation possible, which doesn’t change the actual position of the sprite. It’ll rotate just as you would normally think. In the following example, the anchorPoint is set to ccp(1,1), meaning the sprite will rotate around its top right corner. Simpler than it looksI hope this tutorial was clear and helped you better understand how to use anchor points in cocos2d, and combine them with the position to place the sprites where you like, how you like. Also, by using different anchor points, you learned that it is possible to create different rotating patterns, such as rotating around external points. |
|
来自: 勤奋不止 > 《游戏引擎cocos2d》