深入理解Cocos2d-x的anchorPoint锚点和scale缩放之间的配合方式

来源网址:http://segmentfault.com/blog/hongliang/1190000000722574

如果你有一个Node在一个盒子里,盒子的锚点在左下角,这个Node一开始的时候是这个样:position=(0, 0), anchorPoint=(0, 0), scale=1

深入理解Cocos2d-x的anchorPoint锚点和scale缩放之间的配合方式_第1张图片


然后更改它的scale让它撑满整个区域:position=(0, 0), anchorPoint=(0, 0), scale=1.09

深入理解Cocos2d-x的anchorPoint锚点和scale缩放之间的配合方式_第2张图片

这个时候重新设置它的锚点为右上角(1, 1),你认为会发生什么?按照我的理解,我以为应该是这样:position=(0, 0), anchorPoint=(1, 1), scale=1.09

深入理解Cocos2d-x的anchorPoint锚点和scale缩放之间的配合方式_第3张图片

但事实上,它却是这样!!!:position=(0, 0), anchorPoint=(1, 1), scale=1.09

深入理解Cocos2d-x的anchorPoint锚点和scale缩放之间的配合方式_第4张图片

原因在于,一个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




你可能感兴趣的:(深入理解Cocos2d-x的anchorPoint锚点和scale缩放之间的配合方式)