hello,
i’m trying to detect a ray collision with a plane surface defined by 3 vertices,
i tried but it seams like the detection goes beyond the plane boundaries
var a = (mesh.vertices[mesh.triangles[0]]);
var b = (mesh.vertices[mesh.triangles[1]]);
var c = (mesh.vertices[mesh.triangles[ 2]]);
Plane face = new Plane(a,b,c);
if (face.Raycast(ray, out distance)){
}
ps: i’m looking for a way to achieve this without the use of collisions
the plane is infinite in size.
There are several ways to define the position / orientation of a plane. One of them is by passing three points on that plane.
what you probably want is a raycast against your triangle rather than this infinite plane.
I am not sure if there is something implemented in Unity what you can use (maybe there is).
You can write your own intersection algorithm implementation though. It is probably a good idea to use one which already exist, like the Möller-Trumbore Algorithm.
1 Like
Hello,
thanx for the link , really useful, that is what i’m trying to achieve indeed,
for the code example i posted above i was testing on a triangle with 3 vertices a,b,c , but it seams like “if (face.Raycast(ray, out distance))” does not count boundaries and consider the infinite plane of the triangle instead
of course, because it is a plane and not a triangle you perform the raycast on.
Edit: here is a c# implementation of the algorithm: https://answers.unity.com/questions/861719/a-fast-triangle-triangle-intersection-algorithm-fo.html
1 Like
here is c# version of Möller-Trumbore Algorithm that works pretty well in case someone stumble into this
public static bool Intersect(Vector3 p1, Vector3 p2, Vector3 p3, Ray ray)
{
// Vectors from p1 to p2/p3 (edges)
Vector3 e1, e2;
Vector3 p, q, t;
float det, invDet, u, v;
//Find vectors for two edges sharing vertex/point p1
e1 = p2 - p1;
e2 = p3 - p1;
// calculating determinant
p = Vector3.Cross(ray.direction, e2);
//Calculate determinat
det = Vector3.Dot(e1, p);
//if determinant is near zero, ray lies in plane of triangle otherwise not
if (det > -Mathf.Epsilon && det < Mathf.Epsilon) { return false; }
invDet = 1.0f / det;
//calculate distance from p1 to ray origin
t = ray.origin - p1;
//Calculate u parameter
u = Vector3.Dot(t, p) * invDet;
//Check for ray hit
if (u < 0 || u > 1) { return false; }
//Prepare to test v parameter
q = Vector3.Cross(t, e1);
//Calculate v parameter
v = Vector3.Dot(ray.direction, q) * invDet;
//Check for ray hit
if (v < 0 || u + v > 1) { return false; }
if ((Vector3.Dot(e2, q) * invDet) > Mathf.Epsilon)
{
//ray does intersect
return true;
}
// No hit at all
return false;
}
1 Like