casting rays, layer masks, filter objects

 An edit if you will.. When casting rays with masks/filters, remember the ray will keep going until it hits something...so if you have some junk under your floor geo, it's likely the ray will hit it. So be sure to have a function that checks the hit object somewhere..

 

Some code - 

             LayerMask mask = LayerMask.GetMask("spawnObject");
            
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //cast ray
            RaycastHit hit; //create hit event variable

            if (Physics.Raycast(ray, out hit,50f,mask)) //if ray hits object
            {
                worldPos = hit.point;  //position of ray hit
                Vector3 adjust_y = new Vector3(worldPos.x, worldPos.y+2, worldPos.z);
                Spawn(adjust_y, hit.normal);

              }

 

 

LayerMask mask - here we create  a layer mask, and specify the layer we've created and called "spawnObject". 

Ray ray - we're making a ray called ray and we're casting it from the mouse position on the screen - there are several other ways to do this type of ray casting, including casting it from a specific 3d position, eg the tip of a weapon.

RaycastHit hit - making a hit variable we can access.

 if(Physics.Raycast(ray,out hit, 50f,mask)){  - we're checking if the ray we made has hit anything, sticking the info into "hit", specified a maximum distance to search of 50 (it's a float, so f) and finally we apply the mask, "mask". I found that you must use the distance variable when testing for the layer mask - it doesn't work without it.

The rest of the code is creating the coordinates of the hit location & adjusting it a bit with a y offset, just because. Finally we call a Spawn function which we'd define elsewhere, using the adjusted position coordinate and the normal vector stored in the "hit" variable.

As it stands, this would allow the user to click on the stuff in the "spawnObject" layer. Sometimes you'll want to have the inverse of this. To do this, we just need  to invert the layer mask, which is done using the ~ . ~ is the "bitwise invert" operator. It basically flips 0's to 1's and 1's to 0's. so 001 would flip to 110. For our purposes let's just treat it as an invert and ignore the bitwise bit :D

mask=~mask;

Comments

Popular posts from this blog

setting VFX graph properties using C#

scripting custom render texture creation, assignment, shaders