Enemy dies after hitting the player

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

I made a simple enemy that dies when somped and that kills the player if they collide with an Area2D. The stomping part works but when the player is hit, the enemy also dies, is there something wrong with my code?

 extends KinematicBody2D

onready var alive = get_tree().get_root().get_node("World/Player").alive
onready var spawn_point = get_tree().get_root().get_node("World/Player").spawn_point

func _ready():
    $area_enemy.connect("body_entered", self, "on_area_enemy_entered")
    $hitbox.connect("body_entered", self,"on_hitbox_entered")

func on_area_enemy_body_entered(body):
    if body.name == "Player":
        alive = false
        print(alive)
        body.position = spawn_point
        alive = true 

func on_hitbox_entered(body):
        if body.name == "Player":
            queue_free()
:bust_in_silhouette: Reply From: jtarallo

Hi, Gdscript doesn’t work with reference variables. If you want to modify your player’s alive property from the enemy script, you have to store the player node instead of the alive property. So the code would end up something like this:

extends KinematicBody2D

onready var player = get_tree().get_root().get_node("World/Player")
onready var spawn_point = get_tree().get_root().get_node("World/Player").spawn_point

func _ready():
    $area_enemy.connect("body_entered", self, "on_area_enemy_entered")
    $hitbox.connect("body_entered", self,"on_hitbox_entered")

func on_area_enemy_body_entered(body):
    if body.name == "Player":
        player.alive = false
        body.position = spawn_point

func on_hitbox_entered(body):
        if body.name == "Player" and player.alive:
            queue_free()

EDIT: Added player.alive condition for hitbox entered and enemy death. If not, the enemy will be removed even though the player was hit first.

Thank you for answering so soon, it works now

Guiguis_Galdis | 2020-06-11 15:18

Glad to help

jtarallo | 2020-06-11 16:03