- Home /
Is there a way to detect if an object is being hit by a raycast?
Hello,
I tried looking for another thread, but I couldn't find what I was looking for. Basically, I wanted to know if there is a way for an object to detect if it is being hit by a ray.
I assume using a trigger or collider should work, correct? Do rays collide with colliders or triggers? Can I use them to determine if my object is being hit by a ray?
Thanks alot in advance.
I could test it myself, but I am not at home right now :)
Answer by skovacs1 · Dec 02, 2010 at 04:52 PM
If I read correctly, you're asking if there is a way for an object to know if it has been hit by a raycast, correct?
The short answer is no, because it's rather pointless to inform the object that we hit it with a test, but you could always do that on your own where you do the raycast with something like:
Wherever you raycast:
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit)) {
hit.transform.SendMessage("HitByRaycast",gameObject,
SendMessageOptions.DontRequireReceiver);
}
Whatever cares if it was hit by a raycast:
function HitByRaycast(source : GameObject) {
SayOuchTo(source);
}
You may as well just call the function in the script that cast the ray rather than splitting the code across multiple files and adding the overhead of sending the message when you don't need to.
Excellent answer by skovacs. However I think, there are situations where sending the message to the hit object can be very useful. In fact, that's why I came searching for your answer. Imagine if your game object doesn't want to say 'ouch' immediately it gets hit. But would like to keep a record of the hitter so it can come for revenge at a later time. This is just an example but I do think it can be very useful. Thanks for answer btw.
Answer by Krobill · Dec 02, 2010 at 04:35 PM
you have to add a Collider Component to your GameObject to be able to make a raycast on it. If you want 'perfect' collision detection you'll have to use a MeshCollider. Depending on your mesh complexity and the number of collider you intend to use, it might not be a good idea.
You can raycast against a specific object/collider or raycast against your entire scene and see which object/collider hits first.