Maison  >  Article  >  base de données  >  理解Cocos2d里的anchorPoint

理解Cocos2d里的anchorPoint

WBOY
WBOYoriginal
2016-06-07 15:31:16933parcourir

要解释anchorPoint首先需要理解cocos2d里的坐标系统。在cocos2d中有两个坐标系统,一个是touch input使用的,屏幕坐标系统,其原点在左上角,正方向分别朝右和向下。另一个是屏幕绘制用的,使用opengl坐标系统,其原点在左下角,正方向分别朝右和向上。 一般


要解释anchorPoint首先需要理解cocos2d里的坐标系统。在cocos2d中有两个坐标系统,一个是touch input使用的,屏幕坐标系统,其原点在左上角,正方向分别朝右和向下。另一个是屏幕绘制用的,使用opengl坐标系统,其原点在左下角,正方向分别朝右和向上。

一般来说,我们在游戏中都使用opengl坐标系统,在处理屏幕点击事件时先要将其转换为opengl坐标系统,使用方法如:

1

2

3

voidYourClass::ccTouchMoved(CCTouch*pTouch,CCEvent*pEvent){

mSprite->setPosition(CCDirector::sharedDirector()->convertToGL(pTouch->locationInView()));

}

好了,再来看anchorPoint。

在cocos2d中所有从CCNode派生的对象都有anchorPoint属性,cocos2d使用position和anchorPoint两个值来决定在哪里绘制对象,另外在旋转的时候,也会依赖这个属性以决定如何进行旋转。

 

Positioning

对象的position和anchorPoint默认值都是(0,0),这时对象将绘制在屏幕的左下角,比如下面的代码显示的结果:

1

2

3

4

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

sprite.position=ccp(0,0);

sprite.anchorPoint=ccp(0,0);

[selfaddChild:sprite];

理解Cocos2d里的anchorPoint

如果把anchorPoint发为(-1,-1)之后,结果会是这样:

1

2

3

4

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

sprite.position=ccp(0,0);

sprite.anchorPoint=ccp(-1,-1);

[self addChild:sprite];

理解Cocos2d里的anchorPoint

这张图不是太好理解。

1. anchorPoint的数值单位为是象素单位,而是比例值,取值1表示100%。

2. anchorPoint坐标原点在左下角,(-1,-1)表示在左边一个对象宽度处,下面一个对象高度处。

最后再结合修改position和anchorPoint来看下效果,代码及显示效果如下:

1

2

3

4

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

sprite.anchorPoint=ccp(1,1);

sprite.position=ccp(sprite.contentSize.width,sprite.contentSize.height);

[selfaddChild:sprite];

理解Cocos2d里的anchorPoint

这次把anchorPoint设为(1,1),表示在图像的右上角,同时把position向右上角移动,移动宽度为sprite的width,高度为sprite的height。最终的效果也就相当于把原点设为(0,0)左下角,坐标也设在左下角的位置。

 

Rotation

一般情况下,如果需要旋转对象,最好将其anchorPoint设为(0.5,0.5),这样一般能够获得我们所期望的旋转效果。但有些时候,也可以通过设置anchorPoint来实现一些特殊效果,比如,把anchorPoint设为(1,1)即右上角,对象将会绕下面的红点旋转:

理解Cocos2d里的anchorPoint

如果把anchorPoint设为(2,2),一个离对象右上角一个对象远的地方,那么旋转的时候将会像下面这样:

理解Cocos2d里的anchorPoint



Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn