Home > Enterprise >  What is the best way to return all objects within a 3D area?
What is the best way to return all objects within a 3D area?

Time:07-26

I'm currently working on an FPS and trying to create a "Gamemode" controller that gives the team with the most team members within a defined 3d area a point for their team. My first attempt looks something like:

public class TDM: Gamemode
    {
        private Collider pointArea;
        private Dictionary<Player, int> teamA; 
        private Dictionary<Player, int> teamB;
....
    private int methodNumberOfPlayersOnPoint(List<Player> players)
    {
        int count = 0;
        
        foreach (Player player in players)
        {
              if (pointArea.bounds.Contains(player.transform.position))
            {
                count  ;
            }
        }

        return count;
    }

is there a better way to do this?

CodePudding user response:

I don't have much experience in Unity yet so I'll let someone else provide code, but I believe what you're looking for are Trigger Colliders. You basically want to let the engine itself do the heavy lifting for checking for intersection of your player with the zone.

Then in the method that gets called when the player enters the area you can add them to the count that is being used by your scorekeeping component for calculating point accrual. When the player leaves you remove them from the count.

CodePudding user response:

You can call OverlapSphere which gets all the elements within a sphere. Or a box using OverlapBox or capsule using OverlapCapsule.

 void GettAll(Vector3 center, float radius)
    {
        Collider[] objectsHit = Physics.OverlapSphere(center, radius);
        foreach (var obj in objectsHit )
        {
            // do something for each object
        }
    }
  • Related