Picking faces in 3d - Part 1 - Maths Theory
I’m not sure if this is a standard approach, this is just how I figured it out.
A ray is traced from the camera position along its direction Vector.
In a voxel world a test can be made at unit intervals on X,Y,Z axis to see if a collision with a
face has occurred. The distance of 3 possible collisions is compared. The closes is the hit face.
(this method can be adapted to work with non-axis aligned boxes too)
This example shows how to use parametric equations to make these tests. These are the equations we will use
This example will be shown in 2d for clarity, but unlike equations of line, this method will work exactly the same in 3d.
The camera is located at (1,2.5) has a Vector of (1,-0.25)
That means for each moment of 1 in X, there will be -0.25 movement in Y
We will use the parameter t, which could be visualised as time. After a given time, we will be further along the line. We know where we want to be in x. We are checking all the x planes moving away from the camera in + direction(in this case).
For this example we will be checking x= 6. So x(t) = 6.
Now we have x(t) we can solve for t.
Now we can calculate the y value y(t) where the line will be on x=6. If the value is >box min and <box max position then the face has been hit.
In 3d the Z and Y values have to be checked, both must be within the in and max bounds of the box for there to be a hit.
We then calculate the distance to that point - in 3d Distance = Math.sqrt ( X^2, Y^2,Z^2)
Now test all the Z planes, then all the Y planes. The one with the shortest Distance is the one you hit.
Part 2 coming soon - Java code