What is anchor point? It is hard to understand because we usually look at an image to determine the position of the Image Based on the image center. In cocos2d, the position of an image is determined by two dimensions: position, the center of the image, and anchor point. As long as we figure out their relationships, we will naturally be able to solve them.
Their relationship is as follows:
Actualposition. x = position. x + width * (0.5-anchor_point.x); acturalposition. Y = position. Y + height * (0.5-anchor_point.y)
Actualposition is the position actually displayed on the screen by Sprite, poistion is set by program, and achor_point is set by program.
For details, see the following example 1:
CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];sprite.position=ccp(0,0);sprite.anchorPoint=ccp(0,0);[self addChild:sprite];
The specific effect is as follows:
Based on the formula above: assume that the width of the Sprite is 10.
Actualposition. x = 0 + 10 * (0.5-0) = 5; actualposition. Y = 0 + 10 * (0.5-0) = 5;
(5, 5) the result is the actual position of the current image on the screen.
Example 2:
CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];sprite.position=ccp(0,0);sprite.anchorPoint=ccp(-1,-1);[self addChild:sprite];
The specific effect is as follows:
Based on the formula above: assume that the width of the Sprite is 10.
Actualposition. x = 0 + 10 * (0.5-(-1) = 15; actualposition. Y = 0 + 10 * (0.5-(-1) = 15;
(15, 15) the result is the actual position of the current image on the screen.
Example 3
CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];sprite.anchorPoint=ccp(1,1);sprite.position=ccp(sprite.contentSize.width , sprite.contentSize.height);[self addChild:sprite];
Based on the formula above: assume that the width of the Sprite is 10.
Actualposition. x = 10 + 10 * (0.5-(1) = 5; actualposition. Y = 10 + 10 * (0.5-(1) = 5;
(5, 5) the result is the actual position of the current image on the screen.