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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package { import flash.display.Sprite; import flash.geom.Point; import flash.events.MouseEvent; public class Main extends Sprite { public function Main() { drawHills(2,10); stage.addEventListener(MouseEvent.CLICK,mouseClicked); } private function mouseClicked(e:MouseEvent):void{ graphics.clear(); drawHills(2,10); } // this is the core function: drawHills // arguments: the number of hills to generate, and the horizontal step, in pixels, between two hill points private function drawHills(numberOfHills:int,pixelStep:int):void{ // setting a starting y coordinate, around the vertical center of the stage var hillStartY:Number=140+Math.random()*200; // defining hill width, in pixels, that is the stage width divided by the number of hills var hillWidth:Number=640/numberOfHills; // defining the number of slices of the hill. This number is determined by the width of the hill in pixels divided by the amount of pixels between two points var hillSlices=hillWidth/pixelStep; // drawing stuff graphics.lineStyle(0,0xAAAAAA); graphics.moveTo(0,480); // looping through the hills for (var i:int=0; i<numberOfHills; i++) { // setting a random hill height in pixels var randomHeight:Number=Math.random()*100; // this is necessary to make all hills (execept the first one) begin where the previous hill ended if(i!=0){ hillStartY-=randomHeight; } // looping through hill slices for (var j:int=0; j<=hillSlices; j++) { // defining the point of the hill var hillPoint:Point=new Point(j*pixelStep+hillWidth*i,hillStartY+randomHeight*Math.cos(2*Math.PI/hillSlices*j)) // drawing stuff graphics.lineTo(hillPoint.x,hillPoint.y); graphics.lineTo(hillPoint.x,480); graphics.moveTo(hillPoint.x,hillPoint.y); } // this is also necessary to make all hills (execept the first one) begin where the previous hill ended hillStartY = hillStartY+randomHeight; } graphics.lineTo(640,480); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
package { import flash.display.Sprite; import flash.geom.Point; import flash.events.MouseEvent; import flash.events.Event; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class Main extends Sprite { private var world:b2World=new b2World(new b2Vec2(0,10),true); private var worldScale:int=30; var worldDebugDraw:b2DebugDraw; public function Main() { debugDraw(); drawHills(2,10); stage.addEventListener(MouseEvent.CLICK,mouseClicked); addEventListener(Event.ENTER_FRAME,updateWorld); } private function mouseClicked(e:MouseEvent):void{ drawHills(2,10); } private function debugDraw():void { worldDebugDraw=new b2DebugDraw(); var debugSprite:Sprite = new Sprite(); addChild(debugSprite); worldDebugDraw.SetSprite(debugSprite); worldDebugDraw.SetDrawScale(worldScale); worldDebugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit); worldDebugDraw.SetFillAlpha(0.5); } private function drawHills(numberOfHills:int,pixelStep:int):void{ world=new b2World(new b2Vec2(0,10),true); world.SetDebugDraw(worldDebugDraw); var hillStartY:Number=140+Math.random()*200; var hillWidth:Number=640/numberOfHills; var hillSliceWidth=hillWidth/pixelStep; var hillVector:Vector.<b2Vec2>; for (var i:int=0; i<numberOfHills; i++) { var randomHeight:Number=Math.random()*100; if(i!=0){ hillStartY-=randomHeight; } for (var j:int=0; j<hillSliceWidth; j++) { hillVector=new Vector.<b2Vec2>(); hillVector.push(new b2Vec2((j*pixelStep+hillWidth*i)/worldScale,480/worldScale)); hillVector.push(new b2Vec2((j*pixelStep+hillWidth*i)/worldScale,(hillStartY+randomHeight*Math.cos(2*Math.PI/hillSliceWidth*j))/worldScale)); hillVector.push(new b2Vec2(((j+1)*pixelStep+hillWidth*i)/worldScale,(hillStartY+randomHeight*Math.cos(2*Math.PI/hillSliceWidth*(j+1)))/worldScale)); hillVector.push(new b2Vec2(((j+1)*pixelStep+hillWidth*i)/worldScale,480/worldScale)); var sliceBody:b2BodyDef=new b2BodyDef; var centre:b2Vec2=findCentroid(hillVector,hillVector.length); sliceBody.position.Set(centre.x,centre.y); for(var z:int=0;z<hillVector.length;z++){ hillVector[z].Subtract(centre); } var slicePoly:b2PolygonShape=new b2PolygonShape; slicePoly.SetAsVector(hillVector,4); var sliceFixture:b2FixtureDef=new b2FixtureDef; sliceFixture.shape=slicePoly; var worldSlice:b2Body=world.CreateBody(sliceBody); worldSlice.CreateFixture(sliceFixture); } hillStartY = hillStartY+randomHeight; } } private function findCentroid(vs:Vector.<b2Vec2>, count:uint):b2Vec2 { var c:b2Vec2 = new b2Vec2(); var area:Number=0.0; var p1X:Number=0.0; var p1Y:Number=0.0; var inv3:Number=1.0/3.0; for (var i:int = 0; i < count; ++i) { var p2:b2Vec2=vs[i]; var p3:b2Vec2=i+1<count?vs[int(i+1)]:vs[0]; var e1X:Number=p2.x-p1X; var e1Y:Number=p2.y-p1Y; var e2X:Number=p3.x-p1X; var e2Y:Number=p3.y-p1Y; var D:Number = (e1X * e2Y - e1Y * e2X); var triangleArea:Number=0.5*D; area+=triangleArea; c.x += triangleArea * inv3 * (p1X + p2.x + p3.x); c.y += triangleArea * inv3 * (p1Y + p2.y + p3.y); } c.x*=1.0/area; c.y*=1.0/area; return c; } private function updateWorld(e:Event):void { world.Step(1/30,10,10); world.ClearForces(); world.DrawDebugData(); } } } |
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.
They can be easily customized to meet the unique requirements of your project.






(29 votes, average: 4.86 out of 5)






This post has 21 comments
Chris
Interesting article!
It’s nice to see your ideas on how it was achieved and spreading it :)
I’ve come across a nice github project that was actually trying to achieve the effect aswell and has a really nice result:
https://github.com/haqu/tiny-wings#readme
Maybe it would be nice to try to port that into Flash since it was accomplished using Box2D aswell :]
davidp
wow, this is awesome! great article :)
Chris Moeller
Very nice! I’m also going to be going through your procedural textures tutorials- going to be using them a lot for a big project in the near future.
Thanks for posting this! Lots of ideas based on these two!
Ovidiu
Awesome, awesome article! Never thought this would be so simple!
Thank you, really!
Keep up!
Fintan
cool tutorial. how would you get the tiny bird to always be oriented to the slope of the hill if it was in contact with it?
Ramon Fritsch
Isn’t it too performance intence to have a that many polygons running on box2d inside flash? I’m wondering if you could group some polygons at the top of the hills. I’ve created a game with smooth slopes like that but I couldn’t realise what was the best way to reproduce with a smooth framerate.
Cheers
Emanuele Feronato
@chris: the demo looks god, I’ll try to port it into AS3
@ramon: do you remove polygons when as they leave the stage on the left side?
Farzad
Awesome!
This Week on Twitter and Google+ | Flash Video Traning Source
[...] this post, Emanuele Feronato explains how to use trigonometric functions to build a terrain that seems [...]
patrik
cool, thanks for sharing!
Ant
Purely for the shape generation (no box2d stuff) you could use the BezierSegment class in Flash for smooth and efficient curves
Aeon
Very nice article!! \o/
This same technic is used into cyclomaniacs?
http://www.kongregate.com/games/LongAnimals/cyclomaniacs
“you remove polygons when as they leave the stage on the left side?”
How manage the npcs?
Eric
How about using fractals to generate random and cool looking hills?
I just found this article while doing some oter research and thought it might be perfect to use for this:
http://www.gameprogrammer.com/fractal.html#ptII
You probably then can smooth it out to get more “slidy” hills than just jagged sharp scary hills.
How to create a game like Tiny Wings? Links | sabawgames
[...] http://www.emanueleferonato.com/2011/07/14/create-a-terrain-like-the-one-in-tiny-wings-with-flash-an... [...]
astro75
http://www.sideroller.com/wck/ – animated line arcs demo. Those arcs would improve performance.
Janitha
Just need to know what the “|” does in the following piece of code.
worldDebugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
carmine
i need help please , what program do I need to do this ?
Flash Tutorials von Emanuele Feronato | senäh
[...] Zombies. Als heute morgen im Google Reader ein neuer Artikel von mir aufpoppte, in dem er versucht Tiny Wings als Flashspiel umzusetzen, musste ich das einfach als Anlass nehmen hier mal eine Empfehlung [...]
Javascript physics engine and simulated infinite curve
[...] first saw a technique using Box2D, I’m using the closure-web version (because of the memory leaks fix). In short, I explode the [...]
Javascript physics engine and simulated infinite curve | PHP Developer Resource
[...] first saw a technique using Box2D, I'm using the closure-web version (because of the memory leaks fix). In short, I explode the curve [...]
Creating deformable terrain in cocos2dx with box2d – part 1 | JiffyApps
[...] is here: http://www.emanueleferonato.com/ and her tutorial for creating terrain can be found here: http://www.emanueleferonato.com/2011/07/14/create-a-terrain-like-the-one-in-tiny-wings-with-flash-an… That tutorial may be hard to understand for those using cocos2dx and is not as easy as reading a [...]