cocos2d的anchor小總結和小糾結

來源:互聯網
上載者:User

http://www.cnblogs.com/justinwong/archive/2011/06/09/2076793.html

 

自我感覺對anchor的理解沒問題了,但今天被另外一個問題糾結進去了,這裡先做小總結,後面會說到那個問題。

假設有一個CCSprite A,則:

1. anchor是一個CGPOINT,取值在(0.0f, 0,0f) 到 (1.0f, 1.0f)之間。

2. (0.0f, 0.0f)是這個CCSprite矩形地區的左下角,(1.0f, 1.0f)是右上方。

3. anchor決定了這個sprite的position指的是圖片中哪個部分的位置,比如anchor在(0.0f, 0.0f),position在(100, 100),則這個sprite的左下角將被放在(100, 100)。

4. anchor決定對這個sprite進行旋轉的原點。

5. anchor決定了對這個sprite進行縮放的原點。

問題來了,假設有一個CCSprite B,且A是B的child。

那麼當a.position為(0,0) ,且A和B的anchor都是(0.5f, 0.5f)的時候,A會在B的什麼位置呢?

我當時腦子裡想的是A的圖片的中心在B的圖片的中心,但卻不是這樣,正確結果是這樣:

廢了半天勁,其實就是一個概念上被混淆了,那就是我理所應當的認為B的anchor會是A的position的原點(基點),而實際A的position的原點不受B的anchor的影響,一律都在左下角。

這也就是為什麼,我們要在Layer中心建立一個sprite時,要計算winSize,並把position設定為winSize寬高為一半了。

今天使用了大量CCLayerColor為容器嵌套做UI,發現了另外一些問題,就是CCLayer的anchor與CCSprite的區別:

1. CCLayer的anchor不會影響這個layer的position是自己的哪個角放在父容器上,也就是說,無論CCLayer的anchor為何值,position的值都是這個CCLayer的左下角的位置。

2. 除了1以外,CCLayer的anchor的功能和CCSprite相同。

下面是嘗試用的代碼,通過修改幾個參數值可以很快的瞭解anchor:

-(id) init{    // always call "super" init    // Apple recommends to re-assign "self" with the "super" return value    if( (self=[super init])) {                CCSprite *lvSprite = [CCSprite spriteWithFile:@"Icon-72.png"];        lvSprite.anchorPoint = ccp(0.0f, 0.0f);//        lvSprite.position = ccp(100.0f, 100.0f);        lvSprite.scale = 0.5f;        [self addChild:lvSprite];        CCLOG(@"Layer.anchor.x = %f, Layer.anchor.y = %f", self.anchorPoint.x, self.anchorPoint.y);        CCLOG(@"Layer.position.x = %f, Layer.position.y = %f", self.position.x, self.position.y);        CCLOG(@"Sprite.anchor.x = %f, Sprite.anchor.y = %f", lvSprite.anchorPoint.x, lvSprite.anchorPoint.y);        CCLOG(@"Sprite.position.x = %f, Sprite.position.y = %f", lvSprite.position.x, lvSprite.position.y);        //        CCLayerColor *lvLayerColor = [CCLayerColor layerWithColor:ccc4(255, 0, 0, 255)];//        [lvLayerColor changeWidth:100 height:100];//        lvLayerColor.anchorPoint = ccp(1.0f,1.0f);//        [self addChild:lvLayerColor];                    }    return self;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.