Showing posts with label Triangle. Show all posts
Showing posts with label Triangle. Show all posts

Friday, May 14, 2010

XNA Pick model triangle with ray

You can find GetMouseCursorRay and RayIntersectTriangle on this blog.

public bool PickedTriangle(Ray cursorRay, ref Vector3 intersection, ref float distance, ref int[] triangle)
{
float pickDist = 0.0f; // distance from ray origin to intersection
float pickU = 0.0f; // barycentric coordinate of intersection
float pickV = 0.0f; // barycentric coordinate of intersection

for (int i = 0; i < (this._IndicesCount / 3); ++i)
{
// changed from left handed (DirectX) to right handed (XNA)
Vector3 tri0 = this._transformedVertices[this._Indices[3 * i + 0]];
Vector3 tri1 = this._transformedVertices[this._Indices[3 * i + 2]];
Vector3 tri2 = this._transformedVertices[this._Indices[3 * i + 1]];

// Check if the pick ray passes through this point
if (RayIntersectTriangle(cursorRay.Position, cursorRay.Direction, tri0, tri1, tri2, ref pickDist, ref pickU, ref pickV))
{
if (pickDist > 0.0f)
{
intersection = pickU * tri1 + pickV * tri2 + (1 - pickU - pickV) * tri0;
distance = pickDist;

triangle[0] = 3 * i + 0;
triangle[1] = 3 * i + 2;
triangle[2] = 3 * i + 1;

return true;
}
}
}

return false;
}