Trying to make attack code

Godot Version 4.5

Question

Hi, i’m making my first game and I haven’t really worked with Godot a bunch. I’m making an RPG with attack that looks like this:

func _on_area_2d_body_entered(_body:Node2D):
if Input.action_just_pressed(“attack”):
emit_signal(“enemy_attacked)

It’s really weird because it seems like it should be working… I tried a different input in case it was my keyboard but that didn’t do anything.

All it does is freeze the idle animation for the player.

Any suggestions on what to do?

Hey @lesbean31
Did you try completing the official tutorials for Godot already? Highly recommend to check these out, as they explain the basic principles quite well.

2 Likes

Hi,

action_just_pressed will check if an input is pressed on a single frame. _on_area_2d_body_entered will also be called on the exact frame a collision happened, meaning both behaviours need to happen at the same exact frame to work, which will almost never happen.

I don’t know exactly what you are trying to do gameplay wise, feel free to share more info so that we can help you finding a better way of implementing your feature.


Also agree with @wchc, a few tutorials will help with this kind of stuff.

3 Likes

Add to the onbodyenter… a return
if not attacking:
return

This is good so your attack is called once not mutiple times.
here is my code for good refrerence.

	if is_on_floor() and Input.is_action_just_pressed("attack") and not is_attacking and not jump:
			is_attacking = true
			attack_timer = attack_time
			attack_area.monitoring = true

func handle_attack(delta):
	attack_area.scale.x = facing
		
	if not is_attacking:
		return
	attack_timer -= delta
	if attack_timer <= 0:
		is_attacking = false
		attack_area.monitoring = false

func _on_attack_area_body_entered(body):
	if not is_attacking:
		return
	if body.is_in_group("enemy"):
		if body.has_method("on_destroy"):
			body.on_destroy()

Also adding states Enum is a good way and comparing states in order :+1:

1 Like

Is there any way to make something similar to the body_entered function but to check if the player is still in the area2D?

I watched a few good YouTube tutorials but I’ll gladly check out the official tutorials too! Thanks!

Yes, you can call a flag / bool to say var enemy_in_area
and in process physics check that bool.. and run whatever
and call false when exit and try overlapping aswell

You can check it with Area2D::overlaps_body()