Search Unity

How does Physics2D.OverlapArea choose which Collider2D to return?

Discussion in 'Editor & General Support' started by ErnestoBananez, Aug 11, 2015.

  1. ErnestoBananez

    ErnestoBananez

    Joined:
    Sep 23, 2014
    Posts:
    16
    Hi guys. I'm prototyping a 2D platformer/climbing game, and I've generated a square grid of handholds that the player character can traverse. While climbing, the character will move between 'squares' of 4 handholds, grabbing the upper two with the hands and using the lower 2 as footholds, so that the character's body will be situated in the middle of a 'square' anytime it's idle. I have each individual grip set up so it knows what grip is to each side of it at any time.

    In order to connect with the wall the player will be able to jump in front of it and press the 'grip' button. At this point I need the character to attach to the wall in a way that makes sense. For now I'm just trying to lerp the player's body to the center of one of these squares. I figured I'd use OverlapArea() or OverlapCircle() to find the nearest handhold, but I'm having a problem. Whenever I use these functions and there's more than one Collider2D of type Handhold within the overlap, it returns one seemingly at random. I need it to return the one closest to the center of the cast.

    So, on to my question: How do functions like OverlapArea decide which colliders should be returned, when multiple are within the area? What is it actually doing internally? Anything I can rely on, or is it only to be used when you know there's only going to be one collider within the area?

    I could instead use a function like OverlapAreaAll, and then iterate through each collider found to see which is closest to the center of the cast... but that seems inefficient? Am I wrong in that? Can anyone think of a less expensive way?
     
  2. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    From the documentation of OverlapArea():

    Other than that, you should never rely on behavior that isn't documented.

    Sounds perfectly reasonable. You should also provide a layer mask to have the function pre-filter its results.
     
    ErnestoBananez likes this.
  3. ErnestoBananez

    ErnestoBananez

    Joined:
    Sep 23, 2014
    Posts:
    16
    Thanks man, I don't know how I missed that in the documentation.