要解释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];
如果把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];
这张图不是太好理解。
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];
这次把anchorpoint设为(1,1),表示在图像的右上角,同时把position向右上角移动,移动宽度为sprite的width,高度为sprite的height。最终的效果也就相当于把原点设为(0,0)左下角,坐标也设在左下角的位置。
rotation
一般情况下,如果需要旋转对象,最好将其anchorpoint设为(0.5,0.5),这样一般能够获得我们所期望的旋转效果。但有些时候,也可以通过设置anchorpoint来实现一些特殊效果,比如,把anchorpoint设为(1,1)即右上角,对象将会绕下面的红点旋转:
如果把anchorpoint设为(2,2),一个离对象右上角一个对象远的地方,那么旋转的时候将会像下面这样: