Reputation: 11
I'm making a 2D platformer with player mechanics that depend on the type of tile the Player lands on. I have two types of tiles white and black - if Player lands on a white tile, he has ability A, and when he lands on a black tile, he has ability B. The white and black tiles have their own collision layer each. I'm doing an "OnCollisionEnter2D" which then gives Player the abilities. You can activate or deactivate (make them visible or not) the white and black tile objects. Things go smooth when you land on a white or a black tile, but there are certain places where both tile objects overlap. In the hierarchy black is underneath white and when I run the game I first get collision with black and then I get collision with white (which overrides the black). This is my original intention as I want the white tiles to override the black tiles, but every time Player deactivates and then reactivates the white tile object, the collion order changes - I first get collision with white and then collision with black tile object, so even if the white tile object is on top, Player gets abilities for black tiles. I need to keep both tile objects active. My question is how is the order of collisions decided in Unity and do I have any control over it? I need to be able to tell my game which collision to prefer if there are "simultaneous" (I know they are in fact consecutive) collisions with two overlapping objects.
I tried changing the order of the collision object within the collision layer to no avail. Tried changing the hierarchy of the objects in the Inspector - again to no avail.
Upvotes: 1
Views: 88
Reputation: 46
When they overlap they trigger each others onCollisionEnter2D functions before player hit any of it, right? Then you can use this approach:
public class CollisionManager : MonoBehaviour
{
enum TileType
{
Black, White
}
[SerializeField] TileType tileType;
//Don't forget to make this variable "false" after overlapped white tile leave or destroy or disable or idk anything like that
bool IsThereWhiteTileOverlappedAndThisGameObjectIsABlackTile = false;
private void OnCollisionEnter2D(Collision2D collision)
{
IsThereWhiteTileOverlappedAndThisGameObjectIsABlackTile = collision.gameObject.tag == "White Tile" && tileType == TileType.Black;
if (collision.gameObject.tag == "Player")
{
switch (tileType)
{
case TileType.White:
// Player collided with white tile
// Do what you want here
break;
case TileType.Black:
if (IsThereWhiteTileOverlappedAndThisGameObjectIsABlackTile)
return;
// Player collided with black tile and there is no overlapped object
// Do what you want here
break;
}
}
}
}
Upvotes: 0