0
\$\begingroup\$

I had tried to enlarge the player's collider's radius so that it can detect enemies in a wider range and attack them by shooting. However, it seems like the large collider is also affecting the enemies' ability to detect the player.

How can I make a large radius for the player's remote attack, while keeping the enemies only able to detect an object the size of the player's visible model?

If I add a child object with a trigger collider to detect the attack range, is this a good solution?

Unity capsule surrounded by sphere collider

\$\endgroup\$
2
  • 1
    \$\begingroup\$ What kind of attack? Shooting? Raycast might give you some ideas. \$\endgroup\$
    – Zibelas
    Commented Mar 11, 2023 at 7:23
  • 1
    \$\begingroup\$ I've tried to clarify the question - please feel free to make corrections if I've misunderstood your problem. \$\endgroup\$
    – DMGregory
    Commented Mar 11, 2023 at 14:43

2 Answers 2

1
\$\begingroup\$

Create an array of Colliders called hitColliders.

Use the Physics.OverlapSphere() method to find all the colliders within a given range from the current object's position.

Then in use foreach (Collider hitCollider in hitColliders) to detect your enemy

\$\endgroup\$
3
  • \$\begingroup\$ Specifically you mean Physics.OverlapSphereNonAlloc, right, since that's the version that requires an array be created in advance? \$\endgroup\$
    – DMGregory
    Commented Mar 11, 2023 at 14:55
  • \$\begingroup\$ Yes, Physics.OverlapSphereNonAlloc() can be better than Physics.OverlapSphere() in situations where you need to detect a certain number of colliders within a sphere, it avoids the overhead of creating a new array every time the method is called. \$\endgroup\$
    – fatdrogen
    Commented Mar 11, 2023 at 15:01
  • \$\begingroup\$ is use OnTriggerStay in child better? \$\endgroup\$ Commented Mar 11, 2023 at 15:20
0
\$\begingroup\$

I am not sure if Unity already has this but you may create mask.

You need 2 integers:

  1. int ownType ... 1 bit in integer (mask works for 32 objects = 2ˇ32).
  2. int mask ... with whom object collide

On collision 1st. check if collision is valid to proceed.

\$\endgroup\$
1
  • \$\begingroup\$ The Unity way to do this is to use Layer-Based Collision Detection. Colliders on non-interacting layers won't have their collisions or trigger events processed, so you don't need to manually check the mask in user code. Want to update your answer with a write-up based on that documentation? \$\endgroup\$
    – DMGregory
    Commented Mar 11, 2023 at 14:41

You must log in to answer this question.

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