Search Unity

Collider 2d z Range?

Discussion in '2D' started by migueltuliompg, Aug 12, 2019.

  1. migueltuliompg

    migueltuliompg

    Joined:
    Feb 12, 2018
    Posts:
    63
    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. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    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:
    Aug 13, 2019
    Posts:
    1
    tank
     
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    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:
    63
    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.