anchor point 究竟是怎麼回事? 之所以造成不容易理解的是因爲我們平時看待一個圖片是 以圖片的中心點 這一個維度來決定圖片的位置的。而在cocos2d中決定一個 圖片的位置是由兩個維度 一個是 position 另外一個是anchor point。只要我們搞清楚他們的關係,自然就迎刃而解。
默認情況下,anchor point在圖片的中心位置(0.5, 0.5),取值在0到1之間的好處就是,錨點不會和具體物體的大小耦合,也即不用關注物件大小,而應取其對應比率,如果把錨點改成(0,0),則進行放置位置時,以圖片左下角作爲起始點。
也就是說,把position設置成(x,y)時,畫到屏幕上需要知道:到底圖片上的哪個點放在屏幕的(x,y)上,而anchor point就是這個放置的點,anchor point是可以超過圖片邊界的,比如下例中的(-1,-1),表示從超出圖片左下角一個寬和一個高的地方放置到屏幕的(0,0)位置(向右上偏移10個點纔開始到圖片的左下角,可以認爲向右上偏移了10個點的空白區域)
他們的關係是這樣的(假設actualPosition.x,actualPosition.y是真實圖片位置的中點):
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) 這個結果正是現在圖片中心的在屏幕上的實際位置。
如果以左下角(Opengl座標系的原點)爲參照,就是把圖片的原點錨在了屏幕座標的原點上
例子 二:
- CCSprite *sprite = [CCSprite spritewithFile:@"blackSquare.png"];
- sprite.position=ccp(0,0);
- sprite.anchorPoint=ccp(-1,-1);
- [self addChild:sprite];
具體效果如下:
根據上面的公式: 假設精靈的width = height = 10.
座標方向是opengl的方向(原點在左下角,x向左,y向上爲正)
actualPosition.x = 0 + 10*(0.5 - (-1)) = 15; actualPosition.y = 0 + 10*(0.5 - (-1)) = 15;
(15, 15) 這個結果正是現在圖片中心的在屏幕上的實際位置。
如果以左下角(Opengl座標系的原點)爲參照,就是把圖片的(-10,-10)這個點錨在了屏幕的原點(即圖片的原點錨在了屏幕座標的(10,10)上)
例子三
- 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) 這個結果正是現在圖片中心的在屏幕上的實際位置。
就是把圖片的(10,10)這個點錨在了屏幕座標的(10,10)上
-----------------------------------------------------------------
總結一下, 我們把計算式子轉換一下,
actualPosition.x - position.x = width*0.5 - anchor_point.x*width;
acturalPosition.y - position.y = height*0.5 - anchor_point.y*height;
actualPosition是實際屏幕座標系的座標, position是我們代碼設置的座標.
而 width*0.5 和 height*0.5其實就是圖片的中心點.
這樣看兩邊,其實就等於說是position 相對於 actualPosition的平移, 就是錨點相對於圖片中心的平移.
我們把actualPosition標記爲原點(0,0), 那 position 就是相對於原點的平移量, 變換可得:
position.x = anchor_point.x*width - width*0.5;
position.y = anchor_point.y*height - height*0.5;
也就是說錨點, 本質就是一個圖片中心點平移比例值而已.
它是一個平移比率值, 究竟平移多少, 和圖片具體的 size 相關.