Search Unity

Force field and teams

Discussion in 'Scripting' started by Leonid, Aug 7, 2020.

  1. Leonid

    Leonid

    Joined:
    Aug 20, 2013
    Posts:
    90
    Hello!
    The question of universal and simple forcefield mechanics is bothering me for years.
    Imagine forcefield. It can stop enemy projectiles and lasers (in other words, it is interacting with colliders and raycasts), but allies can shoot through it.
    Corrently, i have used 2 different solutions:
    1) two layer masks - one for allies and one for enemies. Forcefields have layers ForceField_Team1 and ForceField_Team2 Each projetile/raycast can interact only with forcefield with layer of opposite team (projectile of Team0 can interact with forcefield of Team1 and vice versa).
    Pros: relatively fast
    Cons: layers count must be equal to team count. If there are more than 2 teams, things get more complicated.
    2) team id check logic. Forcefield gets a script containing team id. Each projectile checks every collision, and passes through forcefield if its team id equal to that projectile. Each raycast transforms to RaycastAll and checks every hit to determine if forcefield is hitted and if it is enemy forcefield.

    So the question is, is there another, more elegant way to deal with force fields and teams?
    Thanks :)
     
    Last edited: Aug 8, 2020
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    You'd want contacts filtering, where your code can decide before a collision is processed by the physics simulation if it should be ignored. 2D physics support this using ContactFilter2D and the new Unity Physics supports this as well (see
    Overriding intermediate simulation results). There's an experimental build that implements this for PhysX physics as well but there's no ETA on when that could land in a regular release.

    I'm not sure how all these APIs integrate with raycasts, so maybe you'd have to filter raycast hits manually.

    Using layer masks might be the simplest, though. You don't need to define all the layers in Unity, they can be used without setting a name using Physics.IgnoreLayerCollision, which means you could set them up dynamically via code. But you still have to reserve a number of layers and thus limit the maximum number of teams.
     
    Leonid likes this.
  3. Leonid

    Leonid

    Joined:
    Aug 20, 2013
    Posts:
    90
    Thank you! Well, that is great to hear that Unity is working on it.
    Physics.IgnoreLayerCollision will make things easier indeed!