June 2022

3rd Person Camera Movement with Compute Shaders

This is something I was playing with a few years ago, but I just bumped into it again and I thought it was neat enough to share. The problem I was trying to solve here is how to keep a 3rd person camera from colliding with various and/or having the player occluded, while also keeping it relatively smooth.

The classic way to do this is with a simple ray cast, and, well, that’s certainly an effective strategy. The main problem, from my perspective anyway, is it can lead to abrupt distance changes, and the objects that cause those abrupt changes are by definition out of view (because they’re behind the camera), which makes things feel a bit unpredictable.

Most games solve this by just having good level design, but I thought a more interesting way to do it would be to calculate out a smooth transition. One way to do it would just be to shoot out a lot of rays, but that could get expensive and you still have issues with small colliders possibly being between the gaps. I thought using the depth-buffer might help with this, and indeed it does, so here’s a quick demo of what it looks like. The red texture at the top is a (small) depth buffer that’s looking out from the character’s focal point towards the actual camera; and some layers are used so it only renders certain things (ie, things you don’t want the camera to collide with NPCs and small objects).

I’m using a compute shader to calculate the weighted average to figure out the final camera distance. It works fairly well, although it is admittedly a little more expensive than I’d like. At some point I might add it to the asset store, or just create a download for it.