Constructing Terrain Mesh in 2D

I’m currently constructing a 2D side scrolling game with my little brother (he does the artwork), details will be disclosed at a later point. However, I’d like to explain how I did the terrain, as I think it’s a pretty neat technique. If you look at the above drawing, you’ll notice an elf (the player) and a bunch of pink (purple?) dots. The elf can move on the lines between the dots. Imagine there’s a straight line between every dot, that’s the terrain mesh.

This allows us to create the environment in a separate image file, and just place these purple dots wherever you’re allowed to walk. But how does this work?

The program starts by finding the first dot to the left of the elf, and then the dot to the right of the elf – this is just parsing an array, nothing fancy. But how does it know what y-coordinate the elf can have at any given x-position? We’ll denote the player $P$, the left dot $O_1$, and the right dot $O_2$. This means the y-coordinate for the player as a function of x is:

$y(x) = \frac{O_2.x - O_1.x}{O_2.y - O_1.y} \cdot (x- O_1.x) + O_1.y$

The first part may seem familiar if you’ve ever worked with straight lines in high school – this is the formula for calculating the slope between two points, and the next part is the x-coordinate of the player according to the leftmost dot (where x=0 is directly above the dot). The last part ($O_1.y$) is the lower bound – this is the y-position for the player when standing directly above the leftmost dot.

In fact, this formula might seem familiar – it is the well-known $y = ax + b$ formula. The slope $a$ is the slope between the two dots, the x-coordinate $x$ is the x-coordinate according to the leftmost dot, and $b$ is the y-coordinate of the leftmost dot.

Using this method creates a nice, smooth terrain mesh, that’s easy to tweak – you just move the purple dots so the terrain mesh matches the background image. It is literally drag&drop once you’ve implemented the code.

You can try experimenting with this simple setup (like the above image) if you want: https://dl.dropboxusercontent.com/u/19633784/fla.html