0 votes

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()
asked Jun 9 in Engine by Guiguis_Galdis (24 points)

1 Answer

+3 votes
Best answer

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.

answered Jun 9 by jtarallo (376 points)
selected Jun 11 by Guiguis_Galdis

Thank you for answering so soon, it works now

Glad to help

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.