Battle Simulation Logic in ECS #2
Update Group Obstacles And Target On Destruction System
The name of the system is quite a mouth full, but the actual implementation is just a 20 lines of ObjC code. However I don’t want to burden you with ObjC, I will rather write my pseudo language and explain what the system actually does:
Imagine we are in the thick of a battle — town objects are burning, units are deployed in groups and moving toward their targets destroying obstacles on their way. An obstacle is basically a town object which stands in a way between an attacker and the target it needs to destroy.
When we deploy a unit, or rather a unit group we first figure out what should it attack (spoiler alert for the FindGroupTargetOnDeploymentSystem
). Than we move towards it, or start attacking it if it is already in range. Sometimes we also could not find a direct path to the target, so we have a couple of obstacles we need to destroy in order to reach our final target.
Now what is happening when a target which we so desperately want to destroy is finally destroyed? We need to find a new target! This is what this system is all about.
UpdateGroupObstaclesAndTargetOnDestructionSystem
is a reactive system, which is triggered, when a destroy component is added to an entity which already has a town object component. So basically when a town object is destroyed this system is triggered.
In case the system is triggered, we will iterate over all freshly destroyed town objects and over all unitsGroup
which are entities which have Group
Target
and Obstacles
component, but don’t have Retreating
component. Meaning that those are units in active battle and we need to check if they need a new target because the target they have is already destroyed. We also check if the freshly destroyed target is the first obstacle, if so we will shorten the obstacles list.
Now, where is the logic which finds the targets for the units groups you might ask.
This logic is needed in multiple systems and therefor, was introduced as a separate Service TownObjectTargetFinder
, which has a function findTownObjectTargetForGroup
we can call. The function receives an entity which represents a group of units and return a town object entity based on unit group attack priority and closest not destroyed building.
This is it! Next up is FindGroupTargetOnDeploymentSystem
💪.