简单动作
运动之MoveTo和MoveBy
// 创建一个精灵对象
Sprite* xiaozhi = Sprite::create("xiaozhi.png");
// 创建MoveTo动作对象
// MoveTo* moveto = MoveTo::create(float duration, const Point& position);
// duration为动作执行的时间,单位为秒,const Point& position指定要移动的目的坐标
MoveTo* moveTo = MoveTo::create(0.9f, Point(250, 150));
// 精灵执行动作
xiaozhi->runAction(moveTo);
其实,MoveBy和MoveTo用法一模一样,只不过前者是移动了多少,后者是移动到多少。
MoveBy* moveBo = MoveBy::create(0.9f, Point(250, 150));
拉伸之ScaleTo和ScaleBy
用法和MoveTo、MoveBy类似。
// 创建ScaleTo对象
ScaleTo* scaleTo = ScaleTo::create(2.8f, 0.4f, 1.0f);
ScaleTo的三个参数:
float duration:动作的持续时间,单位为秒;
float sx:X方向上的拉伸值;
float sy:Y方向上的拉伸值。
ScaleBy是如何拉伸的?参考: 《Cocos2d-x 3.x 开发之旅》P76
Blink之精灵闪烁
Blink可以使精灵闪烁,并且可以指定闪烁次数,使用方法类似于MoveTo等类。
Size visibleSize = Director::getInstance()->getVisibleSize();
// create a sprite
Sprite* sprite = Sprite::create("sprite.png");
sprite->setPosition(Point(visibleSize.width/2, visibleSize.height/2));
// 创建Blink动作对象
Blink* blink = Blink::create(3.0f, 3);// float duration: 动作的持续时间,单位为秒; int uBlinks:闪烁次数
// 精灵执行动作
sprite->runAction(blink);
注意:Cocos2d-x提供很多动作的API,可参考官方的手册!
复杂动作
重复动作之RepeatForever
Cocos2d-x提供了RepeatForever,使得动作一直重复。
bool HelloWorld::init(){
if(!Layer::init()){
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
// create a sprite
Sprite* sprite = Sprite::create("sprite.png");
sprite->setPosition(Point(visibleSize.width/2, visibleSize.height/2));
this->addChild(sprite);
// 创建一个JumpBy对象,JumpBy是个弹跳动作
JumpBy* jumpBy = JumpBy::create(3.0f, Point(50, 1), 100, 1);
// 以jumpBy为参数,创建一个永久性的重复动作
RepeatForever* repeatForeverAction = RepeatForever::create(jumpBy);
// 以jumpBy为参数,创建一个指定重复次数的动作
Repeat* repeatAction = Repeat::create(jumpBy, 3);
// 精灵执行动作
sprite->runAction(repeatForeverAction);
return true;
}
动作一起做,一边走一边转一边跳之Sequence与Spawn
bool HelloWorld::init(){
if(!Layer::init()){
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
// create a sprite
Sprite* sprite = Sprite::create("sprite.png");
sprite->setPosition(Point(visibleSize.width/2, visibleSize.height/2));
this->addChild(sprite);
// 创建一个移动动作
MoveBy* moveBy = MoveBy::create(2.2f, Point(40, 20));
// 创建一个JumpBy对象,JumpBy是个弹跳动作
JumpBy* jumpBy = JumpBy::create(3.0f, Point(50, 1), 100, 5);
// 创建一个旋转动作对象
RotateBy* roteBy = RotateBy::create(2.5f, 220, 10);
// 创建组合对象,将所有动作链接起来
Action* actions = Action::create(moveBy, jumpBy, roteBy, NULL);
sprite->runAction(actions);
return true;
}
未完待续………