Create a terrain like the one in Tiny Wings with Flash and Box2D

Do you know Tiny Wings?

It’s a cute and addictive game for iPhone featuring a bird with tiny wings – too tiny to fly – which tries to fly anyway using a procedural generated terrain as a ramp.

What makes the game interesting is the physics response of the bird running along slopes.

At a first glance it seems the author is using some kind of physics engine which allows the creation of curves. But at a closer look (or playing on an iPad with zoom mode) we can see hills are made by a series of segments.

So we are going to reproduce such hills with Box2D. But before we dive into physics, some theory.

Tiny Wings hills are generated by trigonometric functions. The more complex the functions, the more interesting the result. In my example I am using a simple cosine, but feel free to try your own formulas and send me your results. I will be happy to publish them.

Once you defined your function, you’ll obviously end with a curve.

The trick is to divide such curve into an amount of slices, having the curve made of segments rather than points.

The higher the number of segments, the better will look the curve, the more CPU consuming will be the game.

In this example, I am assuming I want two hills in a 640×480 stage, with a slice width of 10 pixels.

I won’t use any physics engine, I will just draw two hills:

The script is quite simple and it’s fully commented, and produces this result:

Click on the movie to generate new hills.

Now it’s time to achieve the same results using Box2D. We can say slices are polygons made by four vertices, and we know the coordinates of all vertices, so we just have to create a series of static bodies built starting from such vertices.

To create the polygons, we’ll use the same concept seen in the second part of the slicing tutorial, storing vertices in a Vector, finding polygon centroid starting from such Vector and finally drawing it and placing in the right place.

And this is the script:

The concept is the same of the previous script, we are just building Box2D polygons rather than drawing them on the stage.

And this is the result:

Click on the movie to generate new hills.

Now I have two questions:

1) How would you produce more various shaped hills?

2) How would you scroll/zoom the hills?

Think, meanwhile download the full source code.