2D Meele attack

Godot Version

4.4

Question

I’m trying to implement a combat system. I already have a hitbox and hurtbox component. I also have an attack component that loads an additional scene for the attack type. I have programmed a functional projectile component by using a collision area as the attack range.

Now, my question is how to program a melee attack, such as a sword attack. I don’t think I can use the same pattern with a circle hitbox around my character, because I don’t want the character to hit enemies behind him. My goal is to have a character with multiple animations depending on the direction he’s moving. However, I realized that I don’t know how to move the character’s attack hitbox accordingly.

You could absolutely do that to detect enemies, you just have to then filter the enemies that are not in the right direction. Your direction is a vector, and for each enemy, you can get a vector from the player; with 2 vectors, you have an angle, and if that angle is above a certain threshold (let’s say 90°), that would mean the enemy is considered behind.

However, this would still be hard to set up properly.
A better solution would be to still use a circle detection, but with a circle that is not centered to the character but offset depending on the attack range. To offset the circle, simply get the attack direction and translate the hitbox accordingly. This way, you won’t have to handle behind enemies, as the hitbox itself cannot detect them.
That’s the technique I’m using on my current game, and it works perfectly fine. It’s not very precise, but it’s not what I’m looking so that’s okay for me atm.

Another way you can achieve that is casting multiple raycasts in a cone in the attack direction. For instance, in a cone of 45°, fire 5 rays (with a 45°/5 = 9° offset between each one), get the list of all detected enemies, and attack them.

There are many ways you can do 2D melee attack, I’d suggest you try a simple one to begin with to see if it works, but there’s no absolute right answer here.

1 Like

great answer it cleared up my mind immediately and it works perfectly

1 Like