Finn Eggers - 8 days ago 5
Java Question

# Get position of any point in a triangle

My problem is following:
I've defined a triangle with 3 points.

The coordinate system is defined like this:

• X-Axis heads to the right

• Z-Axis heads out of my screen

This is the most common coordinate system used in OpenGL (i think).
Now I got my triangle. The X and Z values of every point are different.
I need to find the Y coordinate on my triangle by giving the X and Z coordinate.
Someone has written this method and called it barryCentric(Point a, Point b, Point c, Point pos) (I am pretty sure he meant "baryCentric" but fine.

`````` public static float barryCentric(Vector3f p1, Vector3f p2, Vector3f p3, Vector3f pos) {
float det = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z);
float l1 = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.y - p3.z)) / det;
float l2 = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.y - p3.z)) / det;
float l3 = 1.0f - l1 - l2;
return l1 * p1.y + l2 * p2.y + l3 * p3.y;
}
``````

I am not sure if that method makes any sense. He also uses the pos.y value so I guess this is not what I want. Does anyone know an algorithm that can help me with my problem ?

Greetings, Finn

This method makes sense, it is implementation of barycentric interpolation - procedure finds barycentric coordinates of (x,z) point in triangle - l1,l2,l3 here, u,w,v in the linked page.

But implementation contains errors - you a right that one should not use unknown pos.y. Moreover, it is nonsense - subtraction z from y. So change pos.y to pos.z:

``````    float l1 = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.z - p3.z)) / det;
float l2 = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.z - p3.z)) / det;
``````
Source (Stackoverflow)