How do I find Vector3 that ray intersects plane?

Hello I am trying to get the Vector3 location that a ray intersects a plane. I have multiplied the magnitude of the raycast by the transform.forward and when using this in a Debug.DrawRay I get the correct result with the ray pointing from the cameras position to the Vector3 along the plane that I hit. but When I Debug.Log that same point it is off by a couple units.

void ScaleBlock(GameObject instanceGuideBlock, RaycastHit raycastHit){
        Plane plane = new Plane(raycastHit.normal, instanceGuideBlock.transform.position);
        Ray ray = new Ray(cam.transform.position, cam.transform.forward * rayDist);
        if (!plane.Raycast(ray, out float magnitude)){return;}
        Debug.DrawRay(cam.transform.position, planeIntersect, Color.blue, 30f);
        Vector3 planeIntersect = (magnitude * cam.transform.forward);
        Debug.Log(planeIntersect);
       
    }

when testing I got this position for where it is apparently intersecting but the why axis should have been close to 0,5.

(3.24, -1.51, -0.16)

In the attached photo you can see my ray and where it intersects the plane.

I think it’s better to just draw what you need to achieve, because it’s not obvious in your code.
I don’t get the relationships between the object, the plane and the caster.

Raycasts can provide extra info in a RaycastHit struct, and one of the items in there is the hit point. You don’t need to calculate this for yourself.

When you use the Plane struct it tells you the “intersection distance” which you stored in the “magnitude” variable. You would use the Ray you used to do the raycast to get the actual position. Simply pass your “magnitude” to the GetPoint method of your Ray.

Though I’m also curious where your RaycastHit comes from that you currently pass to your method? If it’s the result of the same raycast onto an actual physics collider, you already have the hit point in the RaycastHit. Though if your ray is different from your raycast hit, GetPoint is the way to go.

2 Likes

This is wrong:Vector3 planeIntersect = (magnitude * cam.transform.forward);Unless the camera is at the origin. What you want is:Vector3 planeIntersect = cam.transform.position + (magnitude * cam.transform.forward);

2 Likes

That’s what I thought as well. But then I saw the picture and thought there was more to it.
It’s probably just that.

1 Like

Hi the problem was that I forgot to add the cameras position to the ‘direction’ vector to make it relative to the camera and not the world origin, this is why when using debug.drawRay works because it includes this calculation opposed to debug.drawline which does not. and orion syndrome since you’re wondering im making a building system where you can freely scale blocks. the raycast that i did not show the origin of is just a physics one that i have not yet used in the method. thank you.

forgot to include start + dir in calculations.

1 Like