0
votes

Target: Get the point of intersection of the raycast with the plane's Layer.

The raycast draws a line that intersects the plane (on mouse click).

But the line also intersects everything in its path, so the outcome point is giving the point of intersection with objects other than the plane.

I have assigned the layer of the plane as "Plane" and included in the code the layer of the plane only when raycasting.

        if (Input.GetMouseButton(0))
        {
            RaycastHit hit;
            int layerMask = (1 << 8); // Plane's Layer
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast (ray, out hit, layerMask)) {
                transform.position = hit.point;
            }
        }

What is happening is that the position of the gameObject is overriding its old position until the object is clipping with the camera.

1
Have you tried using a Debug.DrawLine to see what the line is doing and have you checked that the object you're colliding with isn't also on the Plane layer?CasualViking
@CasualViking This is a gif of what is happening. g.recordit.co/w85DuVnHRH.gifYoussof H.
It looks like your red square may also be tagged as "Plane" and so the hit is registering as a point on it, which then moves it, and then this happens several times over.CasualViking
It would also be clearer what's happening if you make the debug lines disappear quickly so you can actually see if they are going through the red thing or not.CasualViking
I am sure that the layer of the cube is set to Default I checked this before but still didn't catch the bug.Youssof H.

1 Answers

0
votes

So, you are passing a ray, a RayCastHit, and a number into Physics.Raycast and it's recognising them like this:

Physics.Raycast (ray, hit, distance)

Any time you do a raycast with a layer mask you need to set the distance of the cast first because that's what all the raycast methods expect as the first number after the hit to use. Here's a version that should work using Mathf.Infinity as the distance:

if (Input.GetMouseButton(0)) {
    RaycastHit hit;
    int layerMask = (1 << 8); // Plane's Layer
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)) {
        transform.position = hit.point;
    } 
}