Raycasting is acting weird.

            for ( int i = 0; i < 20; i++)
            {
                Vector3 rayPos = Vector3.zero + new Vector3(Random.Range(-20, 20), 10, Random.Range(-20, 20));

                Ray ray = new Ray(rayPos, Vector3.down);

                if ( Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, 12) )
                {
                    Vector3 spawnPos = hit.point + new Vector3(0, -18, 0);
                    Quaternion rot = Quaternion.FromToRotation(Vector3.up, hit.normal);

                    GameObject b = Instantiate(barrel, spawnPos, rot);

                    barrels.Add(b);

                    b.transform.DOMoveY(hit.point.y, 3);
                }
            }

I’m trying to get explosive barrels to spawn on my terrain, and the code I wrote worked until I tried to use a layer mask so you wouldn’t have the raycasts hitting things like enemies and spawn floating barrels on top of their head. After making a new layer for terrain (layer 12) and trying to use it as a layermask it all broke, only one barrel gets spawned and the barrel that does get spawned is floating way above the air, no errors, no warnings, nothing. Is there some weird quirk about terrain that I don’t know about?

No but you definitely aren’t using layer masks correctly. Do this:
public LayerMask myLayerMask;Then set the mask up in the inspector (select the layer or layers you want the raycast to hit. It will ignore the rest).

Then use myLayerMask instead of 12.

Alternatively, you can replace 12 with 1 << 12 and it will also work properly. Or you can use LayerMask.GetMask("MyTerrainLayer"). (but replace it with your real layer name)

1 Like

The difference between Layers vs LayerMasks:

https://discussions.unity.com/t/802897/2

“There are 10 types of people in this world: those who understand binary, and those who don’t.”

Thanks guys, completely forgot about layers and layer masks being different and decided to try and be lazy and not make a layer mask variable.

1 Like