0
\$\begingroup\$

I was browsing Wolf3D JS port and bump into that method :

/**
 * @description calculates distance between a point (x, y) and a line.
 * @memberOf Wolf.Math
 * @param {number} x X coord of point
 * @param {number} y Y coord of point
 * @param {number} a Line angle in degrees
 * @returns {number} Distance
 */
function point2LineDist(x, y, a) {
    return Math.abs( (x * SinTable[a] - y * CosTable[a]) >> 0);
}

I think I understand what it does. It gives shortest distance (green on picture) between a line (from angle) and a (x, y) point.

enter image description here

What is not clear to me is how it works. I know a little bit of trigonometry, but I am not able to figure out which trigonometry identity or formula it use. The binary shift is (I think) a quick way to convert a float to an int.

\$\endgroup\$
  • \$\begingroup\$ There's a chance sinTable is just a sin() without using the Math.sin() function, same with cosZable \$\endgroup\$ – Bálint Mar 21 '16 at 13:22
1
\$\begingroup\$

The direction vector of the red line is (CosTable[a], SinTable[a]). It is a unit vector.

Now consider the green line on your drawing. The vector along this line pointing towards (x, y) is orthogonal to the direction vector, and its value is (SinTable[a], -CosTable[a]). It is a unit vector, too.

From there, the distance between point (x, y) and the red line, which is the length of the green line, is the dot product between vector (x, y) and the orthogonal vector. This is where the formula comes from. The abs() call is here because one must account for direction vectors pointing in the other direction.

\$\endgroup\$
  • \$\begingroup\$ Yes you are right, its a simple dot product. It should have popped to my mind. \$\endgroup\$ – tigrou Mar 21 '16 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.