I am making a 2d style platformer but in 3d and I want the player to kill an enemy by jumping on top of it. Right now the enemy is just simple box. I figured out 3 solutions that kind of work.
The first one was creating an empty object, giving it a box collider, checking the is trigger box put it on top of the enemy, and made it a child of the enemy. Then I wrote some code that when the player hit the empty object the parent will be destroyed by checking if the player collided with an object at layer x. That worked but if the player ran into the enemy a few times the enemy would just die so I scrapped this.
The second solution was checking if the player is traveling down and hit the enemy the enemy will be destroyed. The problem with this is that if the player hits the enemy on the side while falling the enemy dies.
private void OnCollisionEnter(Collision collision)
{
Enemy hitEnemy = collision.gameObject.GetComponent<Enemy>();
if (hitEnemy && rigidbodyComponent.velocity.y < 0)
{
Destroy(hitEnemy.gameObject);
}
}
Third solution was a mix of the the first 2 but the enemy still dies when hitting the side but a little higher up:
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy" && rigidbodyComponent.velocity.y < 0)
{
Destroy(other.transform.parent.gameObject);
}
}