- Home /
I need help about raycast and edges
Hi to al.
How I can know the distance between the RayCastHit and the red edge ?
Thanks!
Answer by Statement · Mar 20, 2011 at 10:43 PM
If you know a little math, you can project the point to the line/ray from point A to point B. Then you can measure the distance of the point and the projected point. It's been a while since I did this myself so I can't guarantee it works. :) It might be so you have to replace x with x - a to get the same reference point.
Basically if you have the points a, b and x:
// The vector from a to b. var ab = b - a;
// The point x projected on ab. var xab = Vector3.Project(x, ab.normalized);
// The distance from x to the line ab. var distance = Vector3.Distance(x, xab);
Edit: If above doesn't work it might have to be like this. Or I just dont know a little math after all ^^
// The vector from a to b. var ab = b - a;
// The vector from a to x. var ax = x - a;
// The point ax projected on ab. var xab = Vector3.Project(ax, ab.normalized);
// The distance from ax to the projected xab on line ab. var distance = Vector3.Distance(ax, xab);
Your second script should work ;). I just forgot about the good old dot-product for a sec. So i come up with the geometric approach. I'm not sure what will involve more calculations but this solution at least looks simpler.
Answer by Bunny83 · Mar 20, 2011 at 10:13 PM
You can use Unitys Plane-class to setup a plane that goes through your hit point and is perpendicular to your edge. Just use the vector AB as normal vector and your hit point as origin for the plane (it's the first constructor variant).
When you have your plane, just Plane.Raycast along the edge and you will get your point. You can use Ray.GetPoint with the distance you get from the raycast to calculate the intersection point.
Maybe there's a way to get the point via RaycastHit-barycentricCoordinates but i think that's even harder :D.