2016年6月2日 星期四

0602 cocos2d-x的anchorPoint錨點和scale縮放之間的配合方式

如果你有一個Node在一個盒子裡,盒子的錨點在左下角,這個Node一開始的時候是這個樣:position=(0, 0), anchorPoint=(0, 0), scale=1
然後更改它的scale讓它撐滿整個區域:position=(0, 0), anchorPoint=(0, 0), scale=1.09
這個時候重新設置它的錨點為右上角(1, 1),你認為會發生什麼?按照我的理解,我以為應該是這樣:position=(0, 0), anchorPoint=(1, 1), scale=1.09
但事實上,它卻是這樣!!!:position=(0, 0), anchorPoint=(1, 1), scale=1.09
原因在於,一個Node被設置了scale縮放後,其本身的錨點位置並沒有變,真實的錨點位置還是相對於原大小的位置,所以你注意我上圖中畫紅點的位置,那就是setAnchorPoint(1, 1)之後真實的錨點位置,然後cocos2d-x以新的錨點位置重新執行了scale(1.09)操作,就變成了上圖那個樣。
而左邊超出盒子的部分,其大小就是縮放比例1.09減去1之後乘以Node的原大小,也即
(node:getScale() - 1) * node:getContentSize().width
理解了這個,以後就不會踩坑了。
附一個設置錨點也不改變Node位置的方法:
-- 安全地設置錨點,用於錨點改變後node對象即便設置了scale縮放,其位置也不發生變化
function setSafeAnchor(node, anchorX, anchorY)
  local diffX = anchorX * node:getContentSize().width  * (node:getScaleX() - 1)
  local diffY = anchorY * node:getContentSize().height * (node:getScaleY() - 1)

  node:setAnchorPoint(anchorX, anchorY)
  node:setPositionX(node:getPositionX() + diffX)
  node:setPositionY(node:getPositionY() + diffY)
end

沒有留言:

張貼留言

cocos2dx-lua 建立滑鼠監聽

重要關鍵字  EVENT_MOUSE_SCROLL addEventListenerWithSceneGraphPriority      if IsPc() then --建立滑鼠監聽         local listener = cc.EventListenerMouse...