x


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.

more ▼

asked Dec 02, 2010 at 04:18 PM

Haigotron gravatar image

Haigotron
42 7 6 14

I could test it myself, but I am not at home right now :)

Dec 02, 2010 at 04:19 PM Haigotron
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Dec 02, 2010 at 04:52 PM

skovacs1 gravatar image

skovacs1
11.2k 17 36 110

(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Dec 02, 2010 at 04:35 PM

Krobill gravatar image

Krobill
22 6 4 9

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2979
x2876
x1752
x292
x266

asked: Dec 02, 2010 at 04:18 PM

Seen: 6931 times

Last Updated: Dec 02, 2010 at 04:18 PM