C++ to calculate which point on a triangle is closest to another point

66 Views Asked by At

point1, point2, point3 and object are instances of a custom Vec3 class. Basically, they have X, Y, and Z coordinates.

The goal with this snippet is to consider the three points of a triangle, as well as the object position, and return the closest point on the triangle to the object.

Here are some of the referenced functions:

float dotProduct(const Vec3 &a, const Vec3 &b)
{
    return a.x * b.x + a.y * b.y + a.z * b.z;
}

Vec3 crossProduct(const Vec3 &a, const Vec3 &b)
{
    return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
}

Vec3 normalize(const Vec3 &v)
{
    float length = std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
    return {v.x / length, v.y / length, v.z / length};
}

Here's the main snippet:

// Getting the normal vector of the triangle...
Vec3 edge1 = {point2.x - point1.x, point2.y - point1.y, point2.z - point1.z};
Vec3 edge2 = {point3.x - point1.x, point3.y - point1.y, point3.z - point1.z};
Vec3 normal = normalize(crossProduct(edge1, edge2));

// Calculate the vector from any point on the triangle to the object's position...
Vec3 playerToVertex1 = {object.x - point1.x, object.y - point1.y, object.z - point1.z};
float distance = dotProduct(playerToVertex1, normal);

Vec3 projectedPoint = {
    object.x - distance * normal.x,
    object.y - distance * normal.y,
    object.z - distance * normal.z
};

What I'm getting is this weird phenomenon where it will occasionally return points that seem to be in-line with the X and Z axis, but not the Y axis - leading the "projected" Vec3 to follow along the corners of the triangle, but hover way above them. It's super weird.

It's for a 3D game I'm developing for older hardware. In short, I can "walk" on top of cubes with my player character. I'm using this logic to parse through each triangle in the cube. However, when I try to walk off the cube, my logging shows that it's acting as if there is an invisible wall on all sides.

Anything obvious pop out to any of y'all?

0

There are 0 best solutions below