Cocos2d-x basics

Some articles about Cocos2d-x framework

Movement and other object transformations

Posted at — Sep 24, 2020

In previous articles we learned how to show images and process keyboard event. Now it’s time to do something interesting with objects on the screen.

Imagine you want to move some sprite from one place on the screen to another. You can’t just use setPosition because it will look like teleportation. Instead, you should set new object position a bit closer to the target, then after a very small period of time (milliseconds, maybe) change position again. And again, and again, until after a thousand of small moves the object will appear where you want to see it. That’s not an easy task to implement this in code, so cocos2d-x developers created a special class for it, called Action.

For example, in order to move something you should use a MoveTo class, which is a subclass of Action. It looks like this:

void ActionsDemoScene::sideButtonCallback(Ref *pSender) {
  MoveTo* moveTo = MoveTo::create(2, Vec2(320,240));
  greenUfo->runAction(moveTo);
}

Here greenUfo is a sprite on the scene. moveBy is an action that moves the sprite. The factory method MoveTo::create receives two parameters:

As a result, after pressing a button the green ship will start moving and after some amount of time will get to another place.

Move ship from one point to another

Transformations

There are a lot of possible transformations in cocos2d-x:

Most of the transformations come in two variants: “To” and “By”. The first one receives new parameters (angle, point etc) exactly, and the latter gets a difference between current and desired values.

Easing

By default, the Action changes parameters smoothly and equally, but it may be changed. For example the value may be changed slowly at first and more significantly later; this will give an impression of moving a massive body.

Custom behavior may be implemented with Easing* classes. There are a lot of different variants of them in cocos2d-x.

A small example:

MoveBy* bma = MoveBy::create(6, Vec2(360,0));
EaseIn* bea = EaseIn::create(bma, 1.5f);
blueShip->runAction(bea);

Second parameter for EaseIn constructor defines how notably the changes will be. The larger the easier it will be to see the difference in motion.

Following picture shows the EaseIn and EaseOut comparing to default movement:

Результат модифікаторів [:

Easing

Here the green ship moves as default, blue one gets EaseIn and the red one was eased out.