CoelinG
CoelinG

Reputation: 33

Ignore collision in specific circumstances while still using it as a trigger

I am making a 2D platformer type of game. In this platformer there are both the player and "enemies". The problem arises because: I need both enemies and players to collide with the ground so they don't fall through it. I need to detect when a player collides with an enemy so i can register damage. I need the player to be able to walk through an enemy. Having colliders on the feet is not an option because the player may interact with it. What is the best way to approach this kind of specific collision detection?

Upvotes: 2

Views: 927

Answers (1)

derHugo
derHugo

Reputation: 90649

You can use the Layer Collision Matrix (Edit -> ProjectSettings -> Physics2D) to define exactly which layers can collide with which other layers.

So I would simply use two colliders on the player:

  • one is not a trigger so it can collide with the ground. Put this on a layer playerGround which collides with the ground layer.
  • the other one is a trigger and can collide with the enemy layer. Name it e.g. playerEnemy or something.

Since each GameObject can only have one layer your colliders would have to sit on different objects e.g. like

player (Rigidbody2D)
|--GroundCollider(layer: playerGround)
|--EnemyCollider(layer:playerEnemy, isTrigger)

The enemy layer can collide with both the ground and the playerEnemy.

This way both can walk on the ground. Player can walk through enemies but you can use OnTriggerEnter to detect the collisions with enemies.

Upvotes: 3

Related Questions