How can I kill a enemy upon jumping on him in a 2d platformer?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By potatoLover

I was trying to implement a kill feature where player can jump on top of enemies and enemy will die, I first calculated the y co-ordinate of the player and enemy.After that using if statement i checked if player’s y co-ordinate<enemies y co-ordinate then I make the player die.But problem comes when run towards the player it also makes the enemy die. Here is my sample code.

if collision.collider.is_in_group('enemy'):
    var player_feet = (position + $CollisionShape2D.shape.extents).y
    if player_feet < collision.collider.position.y:
        velocity.y = -200

Player Sprite position
Enemy SPrite Position

Is there any other approach to solve this problem or what should i change in my code?

:bust_in_silhouette: Reply From: Blockmaster27

I am using 3D, but maybe this applies to 2D as well.

The only thing I can think of is by using a downward-facing RayCast, the length of the player, that is only enabled when the player is jumping and turns off when they are not jumping.

When the player hits the ground, the RayCast is disabled so you won’t kill the enemy while on the ground. The length of the RayCast can then be fine-tuned for smoother gameplay.