Search code examples
unity-game-engineraycasting

Raycast point is not on plane Layer (wierd position)?


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.


Solution

  • 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;
        } 
    }