2
\$\begingroup\$

I'm trying to detect where approximately an enemy in my game has been hit. I have added a box collider with a height of 1.8 metres to the enemy.

When the player then shoots, I use a RaycastHit to check if the enemy has been hit. This works fine.

My code is this:

GameObject nHit = _LaserScript.hit.collider.gameObject;

if (nHit != null)
{
    Vector3 nHP = _LaserScript.hit.point; //"hit" is a RaycastHit
    Debug.Log("hit at x: " + nHP.x.ToString() + ", y: " + nHP.y.ToString() + ", z: " + nHP.z.ToString() + "\n");
}

I can relatively easy determine if the enemy has been hit at the head by checking

if (nHP.y > 1.5f)
{
    //headshot detected
}

However, I'm not sure if these coords have to be converted to "local" coordinates.

I tried to determine if I shot the enemy at the left side of his body or on the right side.

To my surprise, the "x" coord of the raycast was always around 1.2, and I have no idea why. I was expecting the x value of the hit to be somewhat between 0 and 0.5f as the collider is not wider than 0.5f.

Basically, I would like a hit at the left "border" of the enemy to have an x value between 0 and 0.1f.

Do I have to convert these hit coordinates (of which the docs say they're world coords) to "local" coords?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Yes, as you found in the docs, raycast hits (as with most physics-related points) are specified in world space coordinates — ie. the coordinate system of your whole scene.

If you want to convert them to the local coordinate space of a particular transform, you'll want to run them through:

Vector3 localHit = transform.InverseTransformPoint(hit.point);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .