- Home /
RaycastHit Triangle Index Problem
I am working on a track editor for futuristic racing game. The vertices, normals, and triangles for the track are all correct, but when I aim a raycast at the track, it gives the wrong triangle index (which I use to align the vehicles with the road). For example, when I fire a raycast around the beginning of the track, it tells me that the triangle I aimed at is about half way across the track.
I have no idea why this is, and I can't figure it out. Raycasts return the correct triangle index for every other mesh collider with no problems, except the meshes from the track editor. I think it could be a bug with Unity 5.0.1, as I have ported a race track from the editor to Unity 4.6 and the triangle indices returned are correct.
I've included this example track from the editor. It requires two materials (one for the road and another for the track's edges) and a mesh collider that simply uses the track's mesh as the collider. (I have a suspicion that because the tracks have two submeshes is why the triangle indices are wrong, but my tests seem to suggest that it might not be.)
Here is the code I am using to get the interpolated normal from the track. Again, it works fine for everything else except the race tracks made by the editor.
//Get Interp Normal on Mesh Collider
public static Vector3 getInterpNormal(RaycastHit hit){
MeshCollider meshCollider = hit.collider as MeshCollider;
Mesh mesh = meshCollider.sharedMesh;
Vector3[] normals = mesh.normals;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3 n0 = normals[triangles[hit.triangleIndex * 3 + 0]];
Vector3 n1 = normals[triangles[hit.triangleIndex * 3 + 1]];
Vector3 n2 = normals[triangles[hit.triangleIndex * 3 + 2]];
Vector3 baryCenter = hit.barycentricCoordinate;
Vector3 interpolatedNormal = n0 * baryCenter.x + n1 * baryCenter.y + n2 * baryCenter.z;
interpolatedNormal = interpolatedNormal.normalized;
interpolatedNormal = hitTransform.TransformDirection(interpolatedNormal);
return interpolatedNormal;
}
If anyone can help me figure this out, I would greatly appreciate it!