- Home /
set ray only when raycast a specific layer
hey! i want to debug a raycast, but only when it hits a specific layer, if it hits somehwere else, do nothing. here is the code so far:
using UnityEngine;
using System.Collections;
public class RaytoMouse : MonoBehaviour {
public float distance = 50f;
//replace Update method in your class with this one
void FixedUpdate ()
{
//if mouse button (left hand side) pressed instantiate a raycast
if(Input.GetMouseButton(0))
{
//create a ray cast and set it to the mouses cursor position in game
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, distance))
{
//draw invisible ray cast/vector
Debug.DrawLine (ray.origin, hit.point);
//log hit area to the console
Debug.Log(hit.point);
}
}
}
}
Answer by wibble82 · Dec 08, 2015 at 12:05 PM
The ray cast system allows you to specify a layer mask. It's described in detail in the docs:
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
But they don't show an example.
The simplest way to use it is to make use of the layer mask utility in unity:
//get the mask to raycast against either the player or enemy layer
int layer_mask = LayerMask.GetMask("Player", "Enemy");
//or this would be just player
//int layer_mask = LayerMask.GetMask("Player");
//or this would be player, enemy or cows!
//int layer_mask = LayerMask.GetMask("Player","Enemy","Cows");
//do the raycast specifying the mask
if (Physics.Raycast (ray, out hit, distance, layer_mask))
{
}
The docs for it are here:
http://docs.unity3d.com/ScriptReference/LayerMask.html
Basically the layer mask is just an integer. For each layer in your game (up to 32), a corresponding 'bit' is set in your mask. The raycast system can use this 32 bit mask to work out what layers you're interested in. Unity's LayerMask utility is a convenient way of constructing these masks so you don't have to think too hard about bits and masks and stuff!
-Chris
Very good answer, saved me a lot of time! Nice Work.
Your answer
Follow this Question
Related Questions
Raycasting and foreach loops 1 Answer
set ray.point as x, y and z float 1 Answer
RaycastHit.transform/collider 1 Answer