Learning C, Day 29 (Terrain Collisions)

Today I worked on adding terrain collisions to the 3D renderer! I looked into 3D collision detection, but it seemed like a lot of work just to have the player walk around on angled surfaces. I had the idea to use pseudo 3D collision detection with a height map.

So I render a depth pass in Blender from a camera looking down on the scene and save it as an image. Then in the renderer, I sample the image at the player’s X and Y to set the player’s height above the ground.

This method has lots of drawbacks:

  • It’s limited by the image resolution and the color space only has 256 steps, so walking up and down surfaces is stepped, not smooth.
  • Doesn’t support moving objects.
  • Doesn’t support walking under objects, because the camera just sees the top of each object.

However, it does have some advantages:

  • Basically no performance impact.
  • Much easier to implement than full 3D collisions.

Well, in theory it should be easy to implement. I’ve run into a bunch of little details which I hadn’t thought of. The biggest challenge is aligning the height map with the terrain. In Blender, I have two empty objects, one at the top left corner of the scene and camera and the other at the bottom right. The idea is that the positions of the empties are the same between Blender and my renderer. Then I can convert the player’s position to a percentage between the two empties and use the percentage to get a pixel from the image. I then use the color of the pixel as a linear interpolation factor between the empties’ Y coordinates.

It’s almost working, but the terrain still seems unaligned.

Leave a comment

Your email address will not be published. Required fields are marked *

Your data is processed in accordance with my privacy policy. Comments are manually approved and may take a while to appear.