0 votes

I try to make a game and I have a problem...

I have the scene of an enemy and connected his attackArea with his kinematicbody. In an other scene ( Player ) I have the variable health.
And when the body entered then I try to subtract the variable health by 10

How is this possible???

I tried with get_node("/root/Player) but it didnt work...

For anybody who needs it, here is my enemy scrpt:

extends KinematicBody2D

export var health = 50
export var speed = 100.0
export var attack_load = 0.4

var velocity = Vector2()
var player = null

var can_attack = true

func _physics_process(delta):
    velocity = Vector2()
    if player:
        velocity = position.direction_to(player.position) * speed
    velocity = move_and_slide(velocity)
    if health <= 0:

func _on_Area2D_body_entered(body):
    player = body

func _on_Area2D_body_exited(body):
    player = null

func _on_AttackArea_body_entered(body):
    if can_attack == true:
        get_node("/root/Player")health -= 5
        can_attack = false
        yield(get_tree().create_timer(attack_load), "timeout")
        can_attack = true 
Godot version 3.4
in Engine by (16 points)

1 Answer

0 votes

Two things, you can either use a singleton or the generally more advisable route which is to create a damage taking function in the player script name it some thing like take_damage(damage : int)and then use the parameter as the amount of damage you want done to the player. In the enemy script you can then call the function on the player like this player.take_damage(5). As a side note the _on_Area2D_body_entered(body) is in a somewhat dangerous position since it doesn't check if the body entered is actually the player, this can be a problem if another enemy or some other physics body or area enters the Aread2D. I suggest doing this by checking the name of the body or checking if the body is in some group that only player characters are in.

by (144 points)
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 webmaster@godotengine.org with your username.