The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

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()
in Engine by (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.

by (380 points)
selected by

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.