Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Collider 2d z Range?

Discussion in '2D' started by migueltuliompg, Aug 12, 2019 at 11:36 PM.

  1. migueltuliompg

    migueltuliompg

    Joined:
    Feb 12, 2018
    Posts:
    34
    Heyo all!

    I'm working on a platformer that involves a lot of switching between z positions, and I was wondering if there's a simple way to only collide with objects that are within a certain distance on the z axis?

    I already know about the layer collision matrix, and I would use that except for the fact that I'm using it to keep the player from colliding with certain objects.

    Any help would be more than... um... helpful!
     
  2. Gambit-MSplitz

    Gambit-MSplitz

    Joined:
    May 16, 2015
    Posts:
    1,181
    I don't know of a great solution, but here's an idea.

    You can call Physics2D.IgnoreCollision() to enable/disable collisions between 2 specific colliders. The tricky part is that you will need to have them enabled or disabled in advance before the objects can physically interact with each other.

    Maybe objects that should check each other's Z position before colliding could have a large trigger collider around them. When the triggers overlap, you can check if the two objects should have physics ignored for their non-trigger colliders based on their difference in Z position.
     
  3. zinpt

    zinpt

    Joined:
    Tuesday
    Posts:
    1
  4. jeffreyschoch

    jeffreyschoch

    Joined:
    Jan 21, 2015
    Posts:
    2,539
    You can use Physics2D checks and provide MinDepth and MaxDepth parameters in the check:
    https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html

    You could alternatively keep track of which objects are on which Z layer using a script. When you switch Z positions, disable objects on the previous layer, and enable objects on the current layer.

    Otherwise I'd suggest using 3D physics.
     
  5. migueltuliompg

    migueltuliompg

    Joined:
    Feb 12, 2018
    Posts:
    34
    I got something that works as long as both players are in the same "z layer."

    Basically it has a trigger around the player, and when an object enters the trigger it checks the z position. If it's in range it sets the objects layer to "Active" and if it's out of range it sets the layer to "Inactive."

    I can only do this with objects that don't need to be in a different layer though.