- Home /
How to hit two object with one raycast?
Hi, I'd like to use an invisible plane as a trigger to call a function (different depending on the side of the screen), but the RaycastHit don't continue through the plane where it need to finally hit the target. Is it possible one raycast (click or touch) to activate the trigger in the plane that is invisible in the front of the target and also hit the target?
Answer by AlucardJay · Jul 19, 2012 at 06:08 AM
Use Layers to selectively choose what colliders a RayCast should detect.
If you need to check the plane first then the world, have a first RayCast layer set to the plane first, then fall through that if statement to another Raycast that is layermasked to ignore the plane, then use that collider info. An example from the docs. To ignore a layer, Check this link, scroll down to Casting Rays Selectively :
http://docs.unity3d.com/Documentation/Components/Layers.html
// JavaScript example from the docs :
function Update () {
// Bit shift the index of the layer (8) to get a bit mask
var layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
var hit : RaycastHit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), hit, Mathf.Infinity, layerMask)) {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) * hit.distance, Color.yellow);
print ("Did Hit");
} else {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) *1000, Color.white);
print ("Did not Hit");
}
}
Thank you! It worked. I didn't know that I could cast two rays in only one click/touch.
Answer by DaveA · Jul 19, 2012 at 11:41 PM
Not that this is better, but you could try Physics.RaycastAll and look at the returned hits.