Why does RaycastHit.barycentricCoordinate not use (x,y,z)-association?

When I set the barycentrics

hit.barycentricCoordinate = new Vector3(0.1f, 0.2f, 0.3f);

I was sure i can expect

(0.1f,0.2f,0.3f)

when I output it with

Debug.Log(hit.barycentricCoordinate);

However, I do get:

(0.7f,0.1f,0.2f)

It is clear that 0.7f=1.0f-0.1f-0.2f. Why does it change the (x,y,z) association to (1.0f-x-y,x,y) ?!?!

Uhm, i’m not sure you really understand what barycentric coordinates are. barycentric coordinates define a point between vertices by specifying the weight of each vertex. The sum of the three components is always 1.0. In the case of RaycastHit.barycentric Coordinate each component is assiciated with one of the 3 corners of the triangle that was hit. So they specify the relative point inside that triangle in 2d space. They do not represent cartesian coordinates.

The barycentricCoordinate od a raycast hit can be used to interpolate any vertex attribute to determine the value at the hit point.

By using the triangleIndex you can determine which triangle was hit. That way you can obtain the 3 indices that form the triangle. With those you can get any vertex attributes of that triangle.

Example:

int[] indices = mesh.triangles;
int I0 = indices[hit.triangleIndex*3];
int I1 = indices[hit.triangleIndex*3 +1];
int I2 = indices[hit.triangleIndex*3 +2];
Vector3[] vertices = mesh.vertices;
Vector3 v0 = vertices[I0];
Vector3 v1 = vertices[I1];
Vector3 v2 = vertices[I2];

Vector3 b = hit.barycentricCoordinate;
Vector3 localHitPoint = b.x*v0 + b.y*v1 + b.z*v2;
Vector3 hitPoint = transform.TransformPoint(localHitPoint);
// hitPoint and hit.point would be the same

Instead of using the vertex positions you could use the texture coordinates, colors, normals, … Though most useful things are already automatically obtained by the RaycastHit structure.

Note that barycentricCoordinate and triangleIndex are only set when you use a MeshCollider. Primitive colliders are not composed of triangles. They are mathematical shapes.