Cast a circle around an object and detect other objects in range

I have a player-controlled object that I am moving around an arena type area. What I want to do is to move the player near an object, and on a particular keypress I would like to display a circular radius around the player object with it being in the exact center that will detect nearby objects (preferably filtered by tag).

I realize there are many ways to accomplish this, but being new to Unity I am trying to find a way that is relatively intuitive to me. Looking at the documentation, Physics2D.CircleCastAll seems like it would fit my needs, but I am unable to test at this time (at work).

A few questions:

  1. Is there a way to colorize the circle that is cast by Physics2D so that it is visible in the scene for testing?

  2. I assume that the return type RaycastHit2D[ ] of Physics2D.CircleCastAll s the location of the collision. Using that am I able to get the exact object that was involved in the collision?

  3. Would there be a better solution to CircleCastAll that would accomplish my needs in a different way?

Any suggesions/tips are welcome. Please don’t give me the code, as I’d like to figure out most of it myself. Thanks in advance!

You’re on the right track. The physics components don’t draw anything, so to question 1, you’ll need to draw the circle in some other way — use a textured Quad or Sprite, for example.

As to question 2, a RaycastHit2D isn’t a location, it’s an object, defined here. It includes several references to the object that was hit (transform, collider, rigidbody), and of course from any of those, you can call GetComponent to get something else.

Cheers,

  • Joe

Yes, you should probably use ‘OverlapCircle’ instead of the CircleCast as you seem only interested in what is overlapping the circle in question.

Also, try to use the ‘NonAlloc’ overloads of these methods which don’t allocate memory and won’t hammer the GC. The ‘All’ methods are the worst as they allocate an array for your results each time.

In closing; I would use Physics2D.OverlapCircleNonAlloc.

1 Like

These tips help me out a great deal. Thanks so much.

1 Like