How to develop Hill Climb Racing with Cocos2d-x – Terrain

this is the first part of the How to develop Hill Climb Racing with Cocos2d-x tutorial. I will presume you have some basic knowledge about programming and of using Cocos2d-x v3.0 engine. I’ll try to follow good coding practises while also giving links to related topics as we progress. Let’s get straight to the point and start deconstruction.

Here’s what we’ll have after finishing this first tutorial:

What is it made of?

Algorithm which creates (x, y) points in 2d space for our upcoming track. These points have been achieved by using sine and cosine functions to create cylindrical shapes. We will later on implement the code, but for clarity let’s go through these concepts one by one.

Physics will define the track which will eventually interact with a car, by keeping the car on top of the track. We will use Box2D for handling physics calculations.

OpenGL meshes are used for visualising the track. Meshes consist of polygons which consist of vertices. The grass on top of the track is a thin slice of mesh drawn on top of the ground mesh. These two meshes are separate, because we don’t want to stretch the grass layer along with the ground mesh.

What is the problem?
Because track is ‘endless’, it is a very long strip of track to draw and calculate physics to. In reality it doesn’t need to be really endless, but we can create array big enough to contain track for so far that the finish line virtually unreachable. If we’d create physics and draw meshes for the whole track, it would jam the CPU and GPU which is not what we want.

We can just generate enough x, y points during game startup in an array, which can be then used to draw and create physics while the player keeps driving forwards. In this tutorial we will be creating x, y points in every 20th pixel, which means iPad2 screen can be filled with track with only 52 keypoints(x, y) 1024px/20px ~= 52. So if we generate 5200 of these points, there will be 100 screenfuls of track to drive and so on.

Ok, so now I’ve introduced you the basic concepts; let’s start coding. I presume you know how to create HelloWorld Cocos2d-x project which on top we will be building this game. We will first write all the code and later implement it on HelloWorld template. Download necessary graphics resources below:

1. Terrain class

Let’s create new class called Terrain in Classes folder. We need to inherit Node class because we will be adding all the sprites etc on this Node which acts as the terrain which scrolls when player drives.

So lets set up Terrain class with following template code. We will implement those unimplemented methods later on.

Now we have created 20000(MaxXYPoints) x, y points which will be the backbone of our track. If you want to play with the track design, this method is where it should be done. In case 20000 points is too low for your purposes, feel free to increase the MaxXYPoints definition in Terrain.h file.

Physics

Cocos2d-x samples include GLES-Render class, which is a tool for drawing shapes of a physic objects. Copy GLES-Render.cpp and GLES-Render.h files from your Cocos2d-x directory, tests/cpp-tests/Classes/Box2DTestBed/ to your project’s Classes folder.

After you’ve done this, we may continue adding physics on our track. Now create method which takes startIndex and endIndex as parameters, which means we can define which portion of the track should physics be calculated. We will modify this method later on to optimise physics calculation properly.

OpenGL meshes

Now we have create X, Y points, which are already used for physics of our track. Next we need to use that same x, y information to generate visuals for the track.
So lets create meshes for the ground and grass. We loaded up textures earlier in the constructor of Terrain, so that part is done. Now we need to create vertices and texture coordinates. We need to create continuous set of polygons next to each other and we need to wrap a texture over and that is what we’re doing next.

If you test this with a mobile platform you might encounter some performance issues. These issues arise from physics calculation and from OpenGL rendering that is done for the whole track at once. Because our track needs to be endless, this kind of solution doesn’t really scale up. If you are not observing these performance issues, tweak up these macros:

#define MaxXYPoints 10000
#define MaxHillVertices 20000

Optimising

glDrawArrays() method takes in the start index and how many triangles should be drawn and this is where we need to take into account the ‘camera’ position. At this point we don’t need Box2d’s debug draw, so we’ll remove those lines. Lets optimise onDraw method:

Physics optimization is little more tricky. We could probably tweak Box2Ds collision algorithm to avoid calculating of the track points which are not visible on the screen, but that sounds like too far fetched.
Our track’s B2Body contains b2EdgeShape fixtures, which are those lines that the GLES debug draws. There is a very performance cheap way to remove those lines one by one from the back and increase one by one on the end. It’s sort of like a moving worm in those early days Nokia phones. So let’s get to it.

Now you should be able to compile this project and see how it looks. Keep tweaking the algorithm that creates the track, so you will have nice track to drive when we create controls, collectibles and car in next chapter!

If you ever read this far, thanks for reading! Feel free to comment and ask any questions you might have and I’ll be happy to answer!

No problem. Just edit void Terrain::generateXYPoints() method, where you set your desired y value in _xyPoints[i].y variable. For example you could generate slight uphill by using this code: _xyPoints[i].y = yOffset + i * 0.5f;

X value is set in _xyPoints[i].x. It needs to be incrementing because the track goes from left to right. If you want to add more length to the track, grow these values:
#define MaxXYPoints 20000 -> 200000
#define MaxHillVertices 40000 -> 400000
Or whatever suits your purposes.

Set different value in GroundStep variable defined in Terrain.h. By default it is 20, which means x points are set in every 20th pixel and if you set GroundStep=5, it means x points are set more closely each other making ground smoother. If you set it 1, it makes the ground as smooth as possible.

Hi, I updated the article with a code that creates gradient layer(similar as the sprite before) which should cover the entire screen. Could you try that out?
HelloWorldScene.h:
//Sprite* _backgroundSprite;
LayerGradient* _backgroundGradientLayer;

Hi. How large terrain do you mean? I suppose you could use https://www.codeandweb.com/physicseditor/. I think one way to do a terrain using Physics Editor would be to first draw the terrain as a black and white image, then use the auto-tracing feature for tracing edges. But again if you are creating very large terrain this might not be suitable.

i have drawn this endless terrain.Now next target is to draw a bike on this terrain .For this i used Box2D and createe a bike body (chesis and wheels ).Box2d return me a .json file that i used to read the bodies from the world.After doing this my bike body successfully drew but started falling.Bike body didn’t hav any contact with grass or ground and fall directly.i used a single world for this.

Can you put this source code on your Github? Please!? I am using cocos2d-x v3.10 and I couldn’t find config.h and every time that I try to compile I found so many bug’s that I could not even understand why…

Hi Joni, I think that now I could understand what is that config.h file used for, this is a kind of an interface to constants in your project? I saw in other tutorials that you have used that file to something like this, I think that I’m learning much more without GutHub, you are right this way is much better, hard at least for me, but much better!

Hi Joni, this tutorial has taught me a lot, today I finally could run your tutorial project, first I thought that my problem was that I don’t know about Box2d, them I learned Box2d a little, them I was thinking that I need to learn about OpenGL, after these months I could understand my bugs, the problem wasn’t in config.h, the problem was in the version of Cocos2d-x 3.10 that has another class called Terrain and cause more than 150 bugs about ambiguity, but I was worth, thank you master!