benmoran56 / esper

An ECS (Entity Component System) for Python
MIT License
544 stars 69 forks source link

Is it possible to attach multiple components of the same type to an entity? #37

Closed Aaron-Fine closed 5 years ago

Aaron-Fine commented 5 years ago

I'm just getting started with esper and ECS systems in general.

I'm working on creating a simple multi agent simulation where various bots have various detectors and behaviors. In my simulation I would like to have the same detector component attached to an entity multiple times with each particular detector looking in a different direction.

As far as I can tell for ent, detector in self.world.get_component(DetectorComponent) only returns one detector for each entity, even if that entity has multiple detectors. How should I iterate over all of the detectors attached to an entity? How can I tell if a particular entity even has multiple detectors?

Shoes01 commented 5 years ago

I am in no way a competent programmer, but I would have the DetectorComponent contain data about the multiple detectors.

benmoran56 commented 5 years ago

Hi Aaron-Fine, Sorry for the late reply to your issue ticket! I don't seem to be getting alerts for some reason, and missed the fact that I had an open ticket.

To answer your question, the default behavior is that you can only have one instance of each Component type on each Entity. I thought about (and tested) supporting subclasses to allow multiples of the same type, but unfortunately this leads to a bit too much performance overhead. As Shoes01 mentioned, you could just add the multiple Detector types into a list, such as:

class DetectorComponent:
    def __init__(self):
        self.targets = []
        ....

And in your Processor, do something like:

for ent, detector in self.world.get_component(DetectorComponent):
    for target in detector.targets:
        ...

Would that work for you?

Aaron-Fine commented 5 years ago

@benmoran56 That's exactly what I ended up doing. At the end there was less code duplication than I had feared. Thank you for looking into it though!