CyanPrime
CyanPrime

Reputation: 5193

Getting distance of a point in a 2d triangle without calculating perpendicular vectors?

Alright, so I'm trying to get the distance of a point in a 2d triangle without calculating perpendicular vectors.

float qd = Vector2f.dot(new Vector2f(pos.x, pos.z),
                        new Vector2f(normal.pos.x, normal.pos.z)) -
           Vector2f.dot(new Vector2f(q.center.x, q.center.z),
                        new Vector2f(normal.pos.x, normal.pos.z));

That's the code I'm using. (Note: it's converting 3f vectors to 2d ones, but you don't have to worry about that). I need the result of the calculation to be between 0 and 1 I.E. 0.5 or something.

If I'm still not explaining right maybe this will help? Axis Example

My question is: How do I get the distance of a point in a 2d triangle without calculating perpendicular vector's distance? I.E. if the triangle is facing up (y = -1) without any tilt I would need the distance in the triangle without any X.

Edit1: About what you're saying, Banthar, This is what I got out of it, and it doesn't work, but it seems like it's close to working.

float d = (float) Math.sqrt( 0 /*cause the two x's should be the same */ + Math.pow(pos.z - q.max.z, 2));   
float h = (float) Math.sqrt( 0 /*cause the two x's should be the same */ + Math.pow(q.min.z - q.max.z, 2)); 

float myDist = d/h;

Upvotes: 0

Views: 1564

Answers (1)

Petar Ivanov
Petar Ivanov

Reputation: 93060

Let's say your triangle is ABC and the point is P. The number you are looking for is the distance from P to AB divided by the distance from C to AB. This is the same as the ratio of the corresponding areas. So you can compute the two areas:

Area(ABP) / Area(ABC)

The best way to compute the triangle area depends on what information you have about your triangle.

If you have the vertices only, then you can use:

Area(ABP) / Area(ABC) = ( Ax*By - Ax*Py + Ay*Px - Ay*Bx + Bx*Py - By*Px ) /
                        ( Ax*By - Ax*Cy + Ay*Cx - Ay*Bx + Bx*Cy - By*Cx )

Upvotes: 2

Related Questions