Sometimes in your game you’ll have to scroll the map when your character moves to some new position. For some games the scrolling creates a really significant part of user experience; I’d recommend to read this article just to understand how important it is.
For your example we’ll take an evil mage animation. Our mage will walk through a long long level that looks like some castle.
The simplest way to implement map scrolling in cocos2d-x is by using the Camera class.
Camera is another Node subclass, so we can use some usual MoveTo action to move it. However, unlike most of the other objects, the camera lives in 3D, so coordinates are specified a bit differently.
That’s how we move the camera to the mage’s position:
cocos2d::Vec2 expectedMagePos; // mage position
<....>
Camera* camera = getDefaultCamera();
const Vec3 currentCameraPos = camera->getPosition3D();
Vec3 newCameraPos = Vec3(expectedMagePos.x, expectedMagePos.y, currentCameraPos.z);
MoveTo* cameraMoveAction = MoveTo::create(1, newCameraPos);
camera->runAction(cameraMoveAction);
Here we create a new position point for the camera; it’s same as the mage position, but also it keeps Z position of the camera.
And that’s all, nothing more. You can see how it works in the demo program. The camera moves each time the mage goes close enough to the right wall:
You could also notice the sceletons here, and there are two important things to say about them. First, some of them move out of the screen borders, so there probably is some waste of CPU resources for calculating their position. You could think it will be better to somehow turn off the animations for all the objects that are too far from the main game character. But this idea is an early optimization, and it’s better to avoid it.
Second, since there are few skeleton persons on the map it will be better to create a special class for a skeleton. Actually, the mage also could use its own class, but to simplify the code I’ve stored all related data in the main class of the scene.
There are two possible ways for creating an object’s class in cocos2d-x:
Both solutions are quite good. Sometimes it comes to more common question “composition over inheritance” and all possible choices have some bad and good sides. Here in the example I’ve used inheritance, but if you prefer composition you can find some useful advices in this article.