Standard Practice for Hitboxes

Godot Version

4.3

Question

Hi everybody. I’ve always had a problem where, say I’m making a 2D Zelda-style game. I’m making the player character swing a sword using the animationplayer to move an Area2D in an arc. The enemy has an Area2D on it that tells it through a signal if an Area2D on physics layer ‘sword’ enters it. When the sword swing starts, I make the sword’s Area2D monitorable. When it ends, I make the Area2D not monitorable.

My problem is, what happens when the location of the sword’s Area2D happens to be inside the enemy already when the sword’s Area2D is made monitorable? There’s no area_entered signal tripped then.

So then I just warp the sword’s Area2D to (-9999999, -9999999) at the end of the swing and warp it back at the start.

But THEN, sometimes the player gets hit by the enemy mid-swing and the animation doesn’t finish, so the 999 warp doesn’t happen, so then I have to set a timer to coincide with the end of the swinging animation instead…

You see my point. Very inelegant. I’m sure I’m just not understanding best practices. If anyone can tear my thinking apart and tell me where it all went wrong it would be much appreciated. What would be an intelligent way to accomplish this?

I’m fairly new to Godot myself, so not sure what the idiomatic way is.
However, these are the ideas I initially thought about:

  1. Always keep the Area2D monitorable, and keep track of what enters and exits in your own data structure. This could be as simple as a var if you only need to keep track of a single hittable thing, or it could be an Array or Dictionary to keep track of everything hittable (a Dictionary would probably make things easier to remove).
    Then when the character swings the sword you just need to check everything in your data structure and decide what to do.
  2. Dynamically create a ShapeCast2D when the character swings the sword and see what it hits.

As I said, not sure if these are idiomatic ways of solving your problem, but both sound like they would be easier to code, maintain and reason about in the future.

2 Likes

Thank you very much. Those are both very good ideas, I had forgotten I’d used the first one before for something, and the second I had never thought of, it sounds like a very good solution too. Thank you!