cocos2d anchor point 锚点解析

anchor point 究竟是怎么回事?

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

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

void YourClass::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {
mSprite->setPosition(CCDirector::sharedDirector()->convertToGL(pTouch->locationInView()) );
}

 之所以造成不容易理解的是因为我们平时看待一个图片是 以图片的中心点 这一个维度来决定图片的位置的。而在cocos2d中决定一个 图片的位置是由两个维度 一个是 position 也就是图片的中心点 另外一个是anchor point。只要我们搞清楚他们的关系,自然就迎刃而解。

他们的关系是这样的: 

actualPosition.x = position.x + width*(0.5 - anchor_point.x); acturalPosition.y = position.y + height*(0.5 - anchor_point.y)

actualPosition 是sprite实际上在屏幕显示的位置, poistion是 程序设置的, achor_point也是程序设置的。

具体看下面的例子一:

CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];
sprite.position=ccp(0,0);
sprite.anchorPoint=ccp(0,0);
[self addChild:sprite];
具体效果如下:

根据上面的公式: 假设精灵的width = height = 10.

actualPosition.x = 0 + 10*(0.5 - 0) = 5; actualPosition.y  = 0 + 10*(0.5 - 0) = 5; 

(5, 5) 这个结果正是现在图片的在屏幕上的实际位置。

例子 二:  

CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];
sprite.position=ccp(0,0);
sprite.anchorPoint=ccp(-1,-1);
[self addChild:sprite];

具体效果如下:

根据上面的公式: 假设精灵的width = height = 10.

actualPosition.x = 0 + 10*(0.5 - (-1)) = 15; actualPosition.y  = 0 + 10*(0.5 - (-1)) = 15; 

(15, 15) 这个结果正是现在图片的在屏幕上的实际位置。


例子三

CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];
sprite.anchorPoint=ccp(1,1);
sprite.position=ccp(sprite.contentSize.width , sprite.contentSize.height);
[self addChild:sprite];


根据上面的公式: 假设精灵的width = height = 10.

actualPosition.x = 10 + 10*(0.5 - (1)) = 5; actualPosition.y  = 10 + 10*(0.5 - (1)) = 5; 

(5, 5) 这个结果正是现在图片的在屏幕上的实际位置。

转载于:https://my.oschina.net/fucku/blog/136405

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值