Help trying to swap area2d(hitbox) position based on mouse position

Godot Version

5.4.1 stable

Question

Hello there, I’m new in Godot and programming in general.
I’m trying to make my character attack hitbox to move dinamically based on mouse position. It certenly works with flipping the sprite2d, but the area 2d is kinda buggy.

Here is the code:

@onready var sprite: Sprite2D = $Sprite
@onready var auto_hit_box: Area2D = $AutoHitBox
@onready var auto_attack_cd: Timer = $AutoAttackCD
var _autoattack_cd: bool = false

func _physics_process(delta: float) -> void:
	velocity.y += delta * GRAVITY
	if Input.is_action_just_pressed("auto-attack"):
		call_deferred("basic_attack")

func basic_attack() -> void:
	if _autoattack_cd == false:
		sprite.flip_h = get_global_mouse_position().x < global_position.x
		auto_hit_box.position.x = -auto_hit_box.position.x if get_global_mouse_position().x \
		< global_position.x	else auto_hit_box.position.x
		_autoattack_cd = true
		auto_attack_cd.start()

Video and an image of the 2D view, since I can’t attach multimedia for being newbie:
video: Video Unavailable
image: https://imgur.com/a/gBqXqAK

Thanks

Buggy in what way?

As I show in the video, the area of the hitbox goes from right to left when I attack. If I have an enemy on my left and I click to my right, the enemy of my left dies, and viceversa. I want the hitbox position to stay on my right or left depending on where I just clicked, so I kill the proper enemy. It’s more clear watching the video I guess, maybe I can’t explain properly because english ain’t my native language sorry

What happens when the timer expires?

I try to prevent spamming the attack

func _on_auto_attack_cd_timeout() -> void:
	_autoattack_cd = false

Edit: I added “if _autoattack_cd == false:” at the function of the main post, being doing tests and forgot to place it back

What happens if you do:

auto_hit_box.position.x = -64 if get_global_mouse_position().x < global_position.x else 64
1 Like

Now looks like it’s working as intended :open_mouth: , what’s going on?

If the mouse is on the left side you were flipping the existing x position of the hitbox regardless of which side it currently is. And if the mouse is on the right side, you were not flipping at all.

You need to use positive/negative constant instead of current position.

1 Like

All right thank you very much!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.