I simply what to tell whether the shot is a headshot or not. on the object I'm throwing at, there are two capsule colliders and a sphere collider. I want to detect if the thrown object hit the sphere collider (headshot)
How can I achieve that?
CodePudding user response:
Multiple options:
Option A: Add 3 empties and add one collider each. Add a script to each of those empties and use the OnCollisionEnter/OnTriggerEnter stuff to detect hits per collider. Or just give each of those colliders a different Tag and compare that using compareTag
.
Option B: You create public/serialized variables and drag the colliders in the slots (inspector). Then, in OnCollisionEnter(Collision collision)
compare the passed parameter with your public variables.
example:
public SphereCollider head;
public CapsuleCollider body;
public SphereCollider feet;
...
void OnCollisionEnter(Collision collision)
{
if(collision.collider == head)
{
// headshot
}
}
It works the same for triggers (OnTriggerEnter).
If you use a Raycast, here is some important tip: Don't confuse hit.collider.transform
. with hit.transform
. (Lets say you wanted to use compareTag on the transforms)
hit.transform
can be the same as hit.collider.transform
if the collider is attached to the same transform as the rigidbody (if any). But you can have colliders as children of your rigidbody. Then, hit.transform
will still return the rigidbodies transform, but hit.collider.transform
will give you the actual child that has the collider attached, that was hit by the ray.