Search code examples
libgdxentity

Share Data between Systems in ECS (Ashley)


I'm currently restructuring my LibGDX-Projekt to fit an ECS-Structure using Ashley. At the moment I have the following System-Structure:

  • InputSystem (handles Player-Input)
  • PhysicSystem (applies velocity to entities, does collisiondetection and moves them)
  • CameraSystem (adjusts the camera to the camera-focus)
  • RenderingSystem (transforms the SpriteBatch with the camera-information and draws all entities)

Now I know that each System is supposed to contains all the logic it needs and is encapsuled to reduce complixity. But I need the camera in the CameraSystem to adjust it, I need it in the RenderSystem to apply the camera-transformation and I need it in the InputSystem to see where the mouse is pointing at. How do you solve this with the ECS-Approach? Can Systems communicate with one another? Should I just use a Singleton called "SharedData" where I dump all the stuff that multiple systems need? Seems a little ugly to me.

Thanks in advance :)


Solution

  • Yes, using a singleton would defeat the purpose of using an ECS in the first place. In an ECS, the approach used is that all shared data is expressed using entities. It is perfectly fine to have an Entity type for which there will only be once instance of it during the lifetime of the game.

    These could then be accessed directly from the Engine when the EntiySystem is added to it. An alternative approach could be to pass commonly accessed entities to the constructor of the systems if it is frequently accessed, in the past I have used this for passing a Box2D World entity.

    I believe my code does a better job of explaining my reasoning so you can have a look at one of my previous games using Ashley. https://github.com/basimkhajwal/LSD

    P.S - My project also includes an event queue for messaging between different entity systems (without passing data, all the data is still encapsulated in Entity classes) which I found to be extremely useful.