Handling Melee and Ranged attacks in platformer

I have a basic platformer with a player that can move and attack and an enemy that doesn’t do anything. How would I handle attacks by the player? I initially thought I could loop through all the enemies and check if they’re in range for melee or whether the ranged projected is touching the enemy hitbox. I plan on having quite a few enemies on the level at once (5-30), so this seems like ti will be very slow. What are some of the common methods to handle this?

Other information that might help:
I’m using Libgdx with Orthogonal TiledMaps and Box2D + Box2D Lights. The hitboxes are currently defined by a rectangle around the enemy.

Is it better to handle attacks (and player/enemy/map collisions) with Box2D or manually?

Any help will be greatly appreciated :slight_smile:

There’s no right way to handle attacks however I would just have a ‘attack radius’ and continuously check to see if here is an enemy within the bounds of that radius and then handle your attacks. You’ll need to loop through all the entities (it won’t be expensive at all, trust me) or you can optimize it a bit to only check if the entities are visible on the screen or actually moving. You can optimize it a bunch in different ways.

if you are using box2d, just add a fixture to the player, that is used as a sensor. Then you just have to store the enemies that are inside it and deal damage to them if the player press attack.

You could have several enemies on the screen - even several times your stated amount, and iterations of a simple calculation such as finding the distance between your character should be quite cheap.

If your map is tiled and you haven’t already optimized it into sectors to avoid rendering unseen portions then this probably won’t be too much of an issue assuming your maps aren’t going to be that large.

Thank you all for the replies. I have another question: I’m using Box2D for the lighting effects only atm and not much else since I can handle attacks by just checking position. Would it be better to use it for tiledmap-player/enemy collisions or do manual collision by checking tile properties? What are the benefits of each?