Need help with killing an enemy

Hello. I am very new to Godot, and i am just wondering what the issue to my problem could be. So my issue is that the enemy won’t die when i click the attack button.

This is the code in the player:

type or paste code here
```extends CharacterBody2D

@onready var sprite_2d = $Sprite2D

@onready var enemy = $"../Enemy"

var SPEED = 250.0
const JUMP_VELOCITY = -900.0

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

func _physics_process(delta):
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta

	# Handle jump.
	if Input.is_action_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		
	var direction = Input.get_axis("left", "right")
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		
	if Input.is_action_pressed("sprint"):
		SPEED = 400
	else:
		SPEED = 250
		
	if Input.is_action_pressed("quit"):
		get_tree().quit()
	move_and_slide()
	
	var is_left = velocity.x < 0
	sprite_2d.flip_h = is_left
	
func _on_area_2d_body_entered(body):
	if Input.is_action_just_pressed("attack"):
		if body.name == "Enemy":
			enemy.enm_DIE()
	
func DIE():
	get_tree().reload_current_scene()

The thing is, it works without the input, and i am very confused about this. I havce checked if the input mapping is correct, and it is!

So if you need more info, or you have the answer to my question. please comment Thanks :)

_on_area_2d_body_entered is a signal triggered. That means that fragment is going to be executed (if poperly wired) just once when the enemy enters, and most likely it is not going to be at the frame you click attack.

You have to understand that the code inside that signal callback is not constantly executed. So you have to think in another approach like enabling that area just when you click attack, for instance. And the rest of the time keeping it disabled.

2 Likes

I … never thought about that! Thanks for the help

If you put a print you will notice better when this code is triggered in the console:

func _on_area_2d_body_entered(body):
    print("Body entered!")
	if Input.is_action_just_pressed("attack"):
		if body.name == "Enemy":
			enemy.enm_DIE()