- Home /
How can I have the player be able to kill an enemy by jumping on top of it?
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);
}
}
Instead of colliders, have you tried a raycast? If you raycast directly down from the player's position by a small amount, it will precisely hit the enemy's head hitbox, and so you can't hit the enemy's side. A head hitbox could be a very narrow collider parented to the enemy collider, but on a different layer, and ignore all colliders - during the raycast - except the head layer.
I got that to work but there is space that the player can hit the enemy and not kill it since the raycast is only in the center of the player. Is it possible to make the raycast the same width as the player?
I don't think so. You'll have to use a collider for that
Answer by Malts_ · May 11, 2021 at 03:01 PM
Have you considered using a smaller collider and putting it in the middle of the enemy's top so that the player has to land squarely on top of the enemy to contact it?
Edit: an alternative solution may be to have another collider for the sides of the enemy. If a collision happens on the sides collider and the damaging collider simultaneously, then ignore it. But if a collision only happens to the damaging collider then register the damage.
Your answer
Follow this Question
Related Questions
OnCollisionEnter Sine Wave to Character 0 Answers
Is there a better way to tell when enemies are dead? 2 Answers
Goal Collision for pong game 0 Answers
Box goes through walls 2 Answers
Distribute terrain in zones 3 Answers