Godot Version
v4.7.stable.mono.official [5b4e0cb0f]
Question
I have very odd bug, that is fixable, but I consider cost of the fix to be not optimal to say the least. I will mostly describe it, since there is too much code involved.
I have 2D top down game, where enemies enter playable area in waves. I need to have reference to every mob in playable area, so I’m using Area2D to track them. Some enemies can move, so if they get out of bounds (intentional), I get rid of them.
I’m using object pool for enemies. It might be an overkill, since there will never be more than 20 enemies at once on the screen, but I’m running Godot .NET, so I really don’t want to trigger Garbage Collector. Once enemy state has been fully reset, they get sent back to object pool.
Current test scenario - single enemy type, 12 enemies in object pool.
- First wave, 12 enemies enter the area.
- Player destroyes them one by one, which sends them back to object pool. Once all have been defeated, it triggers wave 2.
- Another 12 enemies get spawned, but enemy that has been destroyed last gets destroyed offscreen. 11 enemies enter the area.
Enemies are spawned outside of area bounds, and enter the Area2D from the outside. I have managed to track down the source of the problem - that one mob gets detected by Area2D - it enters and exits, which triggers destruction. The issue is that it’s both visually and logically outside - GlobalPosition doesn’t match. This makes it hard to truly fix, since it violates the basic laws of the engine.
Once enemy is destroyed, I call this, which might be useful information:
_collisionShape.SetDeferred(CollisionShape2D.PropertyName.Disabled, true);
SetPhysicsProcess(false);
There are two fixes to this issue, but I find them not optimal:
- Once all enemies are defeated, do not send next wave instantly, but wait at least a second, so mobs have time to settle down. This works and there are no issues anymore, but it does make game pacing worse.
- Make sure enemies from previous wave never enter next wave. Meaning double the object pool size. But this is waste of memory.
I appreciate any ideas that can help me track the real issue and fix it. Worth noting that in my current testing scenario it only affects one enemy, but when I was randomly testing my game it affects up to 2 enemies. I suppose it can affect them all if player manages to destroy entire wave at once.
