总结:
什么是锚点?我们知道Layer,Scene,Sprite,创建它们的时候可以添加一张图,此时我们就把这个图当作一个2维坐标,底部为x轴,高为y轴,设置setAnchorPoint(0,0)代表锚点在坐标(图片)的左下角,即x=0,y=0,使用锚点时可以理解为节点的x,y最大值都为1,设置锚点值相当于设置xy值。
一、锚点的设置
//Layer默认锚点值为(0,0)是因为ignoreAnchorPointForPosition=true;
//Node锚点值是(0.5,0.5),ignoreAnchorPointForPosition=false。
node->setAnchorPoint( Vec2 (0.5, 0.5)); //默认为中心
node->setAnchorPoint( Vec2 (0, 0)); //左下角
node->setAnchorPoint( Vec2 (0, 1)); //左上角
node->setAnchorPoint( Vec2 (1, 0)); //右下角
node->setAnchorPoint( Vec2 (1,1)); //右上角
如上可以看到一个Node或其子类(Scene、Sprite)锚点的设置方法及锚点在Node的位置。
二、锚点的影响
锚点的设置会影响:
位置(position):节点设置的位置即锚点所在位置。
auto scene = Scene ::create();
Size s = Director ::getInstance()->getWinSize();
auto parent = Sprite ::create("HelloWorld.png");
parent->setAnchorPoint( Vec2 (0,0));
parent->setPosition(2*s.width/4,2*s.height/4);//锚点所在位置
旋转(rotation):以锚点为圆心旋转
子节点的添加(addChild):
子节点的锚点总是在父节点左下角,所以设置父节点的锚点不会影响子节点。
动作:对RotateBy、MoveBy等动作的影响,RotateBy会让节点以锚点为中心旋转,MoveBy以锚点为起始运行到指定地点。
所以,当我们添加一个节点时,对节点的位置或相关动作设置都与锚点有关系。
三、测试例子:
auto s = Director ::getInstance()->getWinSize();
auto defaultSprite = Sprite ::create( "pk.png");
auto modifySprite = Sprite ::create( "pk.png");
defaultSprite->setColor( Color3B ::GRAY);
modifySprite->setColor( Color3B ::GREEN);
//设置精灵位置
defaultSprite->setPosition( Vec2 (s.width/4,s.height/2));
modifySprite->setPosition( Vec2 (3*s.width / 4, s.height / 2));
auto smallDefaultPk = Sprite ::create( "pk.png");
auto smallModifyPk = Sprite ::create( "pk.png");
//设置大小
smallDefaultPk->setScale(0.5f);
smallModifyPk->setScale(0.5f);
//设置子精灵,子精灵位于父精灵的左下角
defaultSprite->addChild(smallDefaultPk);
modifySprite->addChild(smallModifyPk);
this ->addChild(defaultSprite);
this ->addChild(modifySprite);
//旋转动作,2秒,360度
auto a1 = RotateBy ::create(2, 360);
auto a2 = ScaleBy::create(2, 2);
auto action1 = RepeatForever::create(Sequence::create(a1,a2,a2->reverse(),nullptr));
auto action2 = RepeatForever ::create( Sequence::create(a1->clone(), nullptr ));
//锚点:只对scale、rotation、skew有效
modifySprite->setAnchorPoint( Vec2 (0.5, 0.5)); //默认为中心
modifySprite->setAnchorPoint( Vec2 (0, 0)); //左下角
modifySprite->setAnchorPoint( Vec2 (0, 1)); //左上角
modifySprite->setAnchorPoint( Vec2 (1, 0)); //右下角
modifySprite->setAnchorPoint( Vec2 (1,1)); //右上角
defaultSprite->setAnchorPoint( Vec2 (1, 0));
defaultSprite->setSkewX(20); //设置倾斜
//执行动作
defaultSprite->runAction(action1);
modifySprite->runAction(action2);