Saturday, January 26, 2013

Random 2D Terrain in XNA

I've been messing around with xna again recently after a brief spell with the UDK. I have been a long time fan of Terraira and was wondering how they managed to create the random terrain for their game. I searched around and came across this. The midpoint displacement algorithm. I tried doing this for a while to no avail. I was confident that I could get it to work given enough time however since going back to college I have very little time for side projects. This got me thinking, there had to be an easier way to do this. Instead of starting off with one line and then breaking it up into smaller and smaller ones, why not just start off small and use a similar technique to randomise the height of the next small line. This was the result.
The white line is the random terrain. I started off by stating the total map width. This is in pixels. Then I stated how detailed I want the map by giving a total number of points to be generated. I then  calculated how far apart the points should be by dividing the width in pixels by the number of points. I then generated the first line. I used the end point of the first line as the start point of the next line and generated a random height for the end point of that line within a certain predetermined range. Repeat this for as long as you want and you get the result above. It is also possible to get a better result by increasing the random height range.
The result is kinda cool. I may post source code someday but for now I will continue my experiments.

Update: As requested here is the source code.

3 comments:

  1. Please post the source code. I'm sure it will help many people who are still getting in the way of game programming (Including me xD)

    ReplyDelete