I have been wondering how slope detection for 2D games such as Gunbound work. The units move according to the terrain, rotating to the gradient of a slope. This morning, after the hype on the terrain generator I made yesterday, I decided to work on it and figure out how slope detection works.
After looking around the internet, I couldn’t really get a concrete example that were detailed enough. So, I decided to make use of the few important information I got my hands on, and came up with my own version
Firstly, here’s what I want to accomplish:
- Units’ movement followed the slope of the terrain they’re standing on.
- Units rotate according to the terrain.
- Units are spawned from midair, so it would have to land on the ground in the correct orientation.
- Units are unable to jump.
One good example that I referred to most was this post made by Emanuele Feronato. Here’s how my unit is set up:
This setup is based on what I learnt from Emanuele’s post. The blue rectangles on the left and right are used to detect whether the unit is hitting any terrain on its either side. The bottom rectangle is used for hit testing against the ground the unit is standing on, and determines if it would fall. Notice that the rectangles on either sides do not reach the bottom of the unit. This allows the unit to “climb” up uneven terrains.
I added two points on either side of the character, as noted by the red dots. These “sensors” are just points defined in my code, with no graphical representation. These will be used to calculate the gradient of the slope, and rotate the character accordingly. Now on to the code.
Here’s a breakdown of what happens every frame.
- Calculate forces (velocity, gravity, friction etc.)
- Check for player input. In our case, the left and right arrow keys.
- If the unit should move, translate it’s x pixel by pixel until its side rectangle hits something, using its x velocity as limit.
- If it hits something, move it upwards along the y axis until the bottom rectangle is clear.
- Increment both sensor’s y position downwards, as well as the unit’s position until it hits the ground and limited by it’s y velocity.
- Now calculate the angle between the two sensors using basic trigonometry, and rotate the player according to the angle.
And now for the sensors,
And of course there’s many other things you might want to check besides this. This is just the general pseudocode I came up, and could be optimized even further. But nevertheless, it still runs at a smooth 30fps on my computer, and here’s the demo, working on the terrain generator. Next, I’ll go on and implement terrain destruction, and maybe come up with a game with it.