I'm trying to write a simple program where a 3D landscape can be walked about with a basic camera. However, I've found it very difficult to do even simple collisions with my terrain. I'm wondering if anybody has encountered a similar issue before and possibly might know how to solve it a better way?
I've seen a lot of 3D collision questions, but I noticed that a lot of the answers are to approximate the mesh objects with spheres or cubes - however I find this impractical with something as complicated as terrain. I'm using a .fbx model of terrain made with blender, grabbing its entire list of vertices, finding the one closest to the camera, and trying to set the camera Y to the vertex Y + a constant. However, I keep running into a bunch of problems such as:
finding the closest vertex is difficult because if the model is too big, distances measured between the camera and the vertices will overflow some variable types, but if the model is too small, distances will often be indistinguishable and inaccurate.
my method is very slow, because the terrain has a lot of detail, so I find myself only checking every 20 vertices or so.
I end up with very bad collision detection because my method appears to be inexact and malfunctioning.
Here's some of my code, if anybody wants to see what I'm doing... (btw the d_check array is a list of vertices of the model, and C is my camera.)
private void BasicCameraCollisionTest(int radius, int offset)
{
float smallest_d = float.MaxValue;
float c_d = 0;
int i_cache = 0;
for (int i = 0; i < d_check.Length; i+=20 )
{
c_d = Vector2.Distance(new Vector2(d_check[i].X, d_check[i].Z), new Vector2(C.position.X, C.position.Y));
if (c_d < smallest_d)
{
smallest_d = c_d;
i_cache = i;
}
}
C.position = Vector3.Lerp(C.position, new Vector3(C.position.X, d_check[i_cache].Y + radius + offset, C.position.Z), 0.02f);
}
If anybody could point me in the right direction, I'd be very grateful. Thanks!