Lens #17: The Lens of the Toy

The lens #17, the lens of the toy from The Art of Game Design: A Book of Lenses written by Jesse Schell. If you buy books through the links in this article I will get a small commission for that.

This lens is about my little character which can pick up weapons, ammo, and other stuff, which can walk, jump and shoot.

I have to answer the following questions

  • If the game had not goal, would it be fun at all? If not, how can I change that?
  • When people see my game, do they want to start interacting with it, even before they know what to do? If not, how can I change that?

It’s fun for me to walk around and shoot enemies. It is simple enough to “get it” and interact with it. Due to the COVID-19, there are no gameshows where I could test if people would like to interact with my game. But the bar should be pretty low to give it a try. But the game world is not interactive enough to just enjoy walking around and explore the levels without any goal.

The game world needs more things we can interact with. Like flying paper in an office space or dust and little debris when walking around. Also shooting should have more impact on the game world.

The outcome of this chapter will lead to a couple more topics for Lens #16: The Lens of Risk Mitigation as I have to try them out quickly which means more prototyping. Prototyping is a fun thing to do actually and with ESC (see also my articles about ESC) it is a piece of cake.

A selection of ideas

  • Destructible stuff
  • Attacking dash
  • Water which includes swimming and diving
  • Whirling paper when rushing through an office space
  • Whirling dust and debris along the way when we shoot
  • A sleeping animation if just standing around

I get a small commissions for purchases made through the following links, I only have books in this section which I bought myself and which I love. No bullshit.

ECS Pattern: Damage System

Writing games is often about dealing with health and damage. With entity component system this is fun to do. Furthermore you can give any entity health or damage any time, it is literally only adding the health or damage or both component to that entity.

Bullets And Characters

To handle health and damage we need health, damage, position, and shape components for the involved entities. A bullet usually does have a damage component besides a position and its shape. A character usually does have a health component besides a position and its shape. The damage system handles these entities and calculates the new damage and health of the involved entities. I usually remove the damage entity a soon it hits something, but if you think of a spell or an ax this is not necessarily true. For a bullet, you might add a very short decay component to let the bullet have a physical impact on the body it hits (read here about the decay pattern) before it vanishes.

A Monkey And Doctor Zaius

For this example I use jMonkeyEngine and Zay-ES. Zay-ES features EntityContainer with an update method which takes care of all created, updated and deleted entity and it provides an array of all entities which are currently in the set (not removed). This makes the code super easy. If your ECS system doesn’t have then you probably have to do a bit more leg work.

Components

I shortly introduce the components we will need. The components are pure data without methods that operate on this data which is very different from the OO programming paradigm.

Health

We just store the amount of health in this component. Furthermore, we define -1 as immortal (for concrete walls for example).

public class Health implements EntityComponent {
    static public int IMMORTAL = -1;
    private Integer health;
    public Health(Integer health) {
        this.health = health;
    }
    public Integer getHealth() {
        return health;
    }
}

Damage

We store the amount of damage in this component, that’s it.

public class Damage implements EntityComponent {
    private final int damage;
    public Damage(int damage) {
        this.damage = damage;
    }
    public int getDamage() {
        return damage;
    }
}

Position

And the position component holds the current 3D location (read my first ECS post how to move objects around).

public class Position implements EntityComponent {
    private final Vec3d location;
    public Position(Vec3d loc) {
        this.location = loc;
    }
    public Vec3d getLocation() {
        return location;
    }
}

Shape

And then finally the shape. To make our life simple we just have sphere objects with a radius.

public class SphereShape implements EntityComponent {
    private double radius;
    public SphereShape(double radius) {
        this.radius = radius;
    }
    public double getRadius() {
        return radius;
    }
}

Damage Entity Set

In the damage system we keep two sets of entities. The first set called the DamageContainer handles all entities with a position, shape and damage component.

    private class DamageData {

        EntityId entityId;
        AABB aabb;
        Vec3d location;
        int amount;
    }

    private class DamageContainer extends EntityContainer<DamageData> {

        DamageContainer(EntityData ed) {
            super(ed, Damage.class, Position.class, SphereShape.class);
        }

        Stream<DamageData> stream() {
            return Arrays.stream(getArray());
        }

        @Override
        protected DamageData addObject(Entity entity) {
            DamageData result = new DamageData();
            result.entityId = entity.getId();
            result.amount = entity.get(Damage.class).getDamage();
            updateObject(result, entity);
            return result;
        }

        @Override
        protected void updateObject(DamageData data, Entity entity) {
            SphereShape sphereShape = entity.get(SphereShape.class);
            data.location = entity.get(Position.class).getLocation();
            Vector2 center = new Vector2(data.location.x, data.location.y);
            data.aabb = new AABB(center, sphereShape.getRadius());
        }

        @Override
        protected void removeObject(DamageData t, Entity entity) {
        }
    }

The data we want is the entity id (to be able to get rid of), the location, amount of damage, and an AABB object for simple collision calculation.

Health Entity Set

On the other hand, we have the health set we call it HealthContainer and it goes like this

    private class HealthData {

        EntityId entityId;
        AABB aabb;
        int amount;
    }

    private class HealthContainer extends EntityContainer<HealthData> {

        HealthContainer(EntityData ed) {
            super(ed, Health.class, Position.class, RectangleShape.class);
        }

        Stream<HealthData> stream() {
            return Arrays.stream(getArray());
        }

        @Override
        protected HealthData addObject(Entity entity) {
            HealthData result = new HealthData();
            result.entityId = entity.getId();
            result.amount = entity.get(Health.class).getHealth();
            updateObject(result, entity);
            return result;
        }

        @Override
        protected void updateObject(HealthData data, Entity entity) {
            SphereShape sphereShape = entity.get(SphereShape.class);
            data.location = entity.get(Position.class).getLocation();
            Vector2 center = new Vector2(data.location.x, data.location.y);
            data.aabb = new AABB(center, sphereShape.getRadius());
        }

        @Override
        protected void removeObject(HealthData t, Entity entity) {
        }
    }

The data we want is the same as for the DamageContainer, the entity id (to be able to get rid of it as well), the location, amount of health and an AABB object for simple collision calculation.

The Update Loop

In the update loop we now update the HealthContainer and the DamageContainer and then we loop over all health entities and inside that we loop over all damage entities and calculate the new Health and Damage component. In our case, we remove the Damage component from the entities on collision and only calculate the new Health component.

   @Override
    public void update(float tpf) {
        healthConatiner.update();
        damageContainer.update();

        healthConatiner.stream().forEach(h -> {
            damageContainer.stream()
                    .filter(d -> !d.parentId.equals(h.entityId))
                    .filter(d -> d.aabb.overlaps(h.aabb))
                    .forEach(d -> {
                        handleHealthAndDamage(h, d);
                    });
        });
    }

Calculus

Let’s look into how we handle health and damage. First we check if the health entity is immortal like a concrete wall and skip the calculation. If the health entity is not immortal we calculate the new health and remove the health entity if the health is equal or below zero. In the end we remove the damage entity as it is used up on collision.

    private void handleHealthAndDamage(HealthData health, DamageData damage) {
        if (health.amount != Health.IMMORTAL) {
            health.amount = health.amount - damage.amount;
            if (health.amount > 0) {
                ed.setComponent(health.entityId, new Health(health.amount));
            } else {
                ed.removeEntity(health.entityId);
            }
        }
        ed.removeEntity(damage.entityId);
    }

Benefit

If your game designer has the famous idea at the last minute possible that your weapons should also be able to destroy the furniture you will not spend hours or days making this happen as you simply can add health to these furniture entities and you are done. Because the code is already in place which handles these entities on collision. This is the actual beauty of the entity component system.

I’m Reading

I’m currently reading the self-published Data Oriented Design from Richard Fabian to get me a deeper insight how to design games with entity component system or as the book title says data-oriented design. A very interesting and cool topic so much different from what I learned with OO approaches. Data-oriented design not only improves the execution time but also your developing performance. Counts especially for games with its short update cycle and the game data which is changing constantly.

The End

You can extend and tweak this example as you like. Go wild.

In case you have questions or suggestions, let me know in the comments below.

Twitch Channel ia97lies

I have a twitch channel and I plan to develop my game from time to time life on this channel. I will not comment on what I’m doing but rather would like to interact with you, just write on the chat all the questions you have and I try to explain in the lifestream. As well as suggestions or improvements are welcome. Just to talk my self or to hidden people isn’t a too nice experience and feels a bit unnatural.

https://www.twitch.tv/ia97lies

I’m looking forward to this out-of-my-comfort-zone experience.

One more thing, I do this game in Java, jMonkeyEngine, Zay-es, Lemur,libgdx-ai, dyn4j and feather. Of course for the models I use blender.

I offer as well test driven development sessions, just let me know down in the comments if you would be interested. Or directly on my twitch channel. I don’t do test driven development for my personal stuff as I’m a one-man-show-game-developer, and I have a different focus than at work. But it would be a completely different story if I work with someone together. If there is interest I prepare something or do it while developing my game All Fucked Up.

I do it in Swiss-German, German and English, depends on the people joining. I’ll see it in the chat 🙂

I’ll be streaming between 8-9 PM CEST on Sunday eve.

ECS Pattern: Follow Entity

When I write games I have always something following something else. The camera follows a hero. Light follows ghost. Goody follows the space ship. Weapon follows the player. And so on and so on. This is a very common pattern in games.
In the object-oriented world, I would probably have a reference to the object which is "attached" to me, like the gun or lamp or whatever it is. In an entity component system I go the other way around, the attached item does have a link to the entity it has to follow. Once you have your system which makes it happen, that every item entity with a link to another entity will follow that other entity you will be able to let nearly everything follow anything else with literally one line of additional code, well most often.

Lemings

Precondition

You already know what an entity component system is if not this article EntityComponent System is Crazy Cool migth give you a clue. I do all my examples in Java, but it should easily be adaptable to whatever own language you have. Also, the ECS might differ, I use Zay-ES, but as well you can probably easily make the link to your implementation of an ECS.

Position of Your Leming

The objects which lead and those which follow need a position component to store the location and the orientation of the entity. This component is set on every frame to make the thing move around. And yes it is always a new instance, no reuse. And java seems to be smart and efficient enough not to have any issue with very short-living objects. Components do have intentionally no setter methods!

public class Position implements EntityComponent {

    private final Vec3d location;
    private final Quatd facing;

    public Position(Vec3d loc, Quatd quat) {
        this.location = loc;
        this.facing = quat;
    }

    public Vec3d getLocation() {
        return location;
    }

    public Quatd getFacing() {
        return facing;
    }

    @Override
    public String toString() {
        return "Position[location=" + location + ", facing=" + facing + "]";
    }
}

Link to Another Leming

Now the object which shall follow another object needs a follow component

public class Follow implements EntityComponent {

    private final EntityId parent;

    public Follow(EntityId parent) {
        this.parent = parent;
    }

    public EntityId getParent() {
        return parent;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "[parent=" + parent + "]";
    }
}

I just store the entity id I want to follow and that’s it.

I Follow You

Now we need a follow system which handles the linked entities. I will have to take care of all entities with a position and a model component and all entities with a position, link, and model component. I will call them leaders and followers.
The followers will be iterated and checked if they have a link to one of the leaders.

Set It Up

For this, I only need the entity data and two Zay-ES containers, one to hold the follers and one to hold the leaders.

public class FollowSystem extends BaseAppState {

    static Logger LOG = LoggerFactory.getLogger(FollowSystem.class);
    private EntityData ed;
    private FollowerContainer followerContainer;
    private LeaderContainer leaderContainer;

    @Override
    protected void initialize(Application app) {
        ed = main.getStateManager().getState(EntityDataState.class).getEntityData();
    }

    @Override
    protected void cleanup(Application app) {
    }

Start/Stop It

When we enable this system we instantiate and start the follower and leader container.

    @Override
    protected void onEnable() {
        followerContainer = new FollowerContainer(ed);
        followerContainer.start();
        leaderContainer = new LeaderContainer(ed);
        leaderContainer.start();
    }

    @Override
    protected void onDisable() {
        followerContainer.stop();
        followerContainer = null;
        leaderContainer.stop();
        leaderContainer = null;

Every Frame

On every frame, I update the follower and leader container to get all added, updated, and removed followers and leaders. To update all follower’s positions I simply loop over the followers, see if their leader does exist in the leader container, get the leader position, and store this position in the follower’s position.

    @Override
    public void update(float tpf) {
        followerContainer.update();
        leaderContainer.update();

        followerContainer.stream().forEach(follower -> {
            LeaderData leader = leaderContainer.getObject(follower.leader);
                        if (leader != null) {
                ed.setComponent(follower.id, new Position(leader.location));
            }
                });
    }

Leaders

The leader’s container keeps track of all the entities which do have a model and a position component, the code is very simple and straight forward.

    class LeaderData {
        Vec3d location;
    }

    class LeaderContainer extends EntityContainer<LeaderData> {
        LeaderContainer(EntityData ed) {
            super(ed, ModelType.class, Position.class);
        }

        Stream<LeaderData> stream() {
            return Arrays.stream(getArray());
        }

        @Override
        protected LeaderData addObject(Entity entity) {
            LeaderData result = new LeaderData();
            updateObject(result, entity);
            return result;
        }

        @Override
        protected void updateObject(LeaderData data, Entity entity) {
            SpawnPosition position = entity.get(Position.class);
            data.location = position.getLocation();
        }

        @Override
        protected void removeObject(LeaderData data, Entity entity) {
        }
    }

Followers

The container is even simpler, we are only interested in entities which do have a follow component and store our entity id and the leader’s entity id.

    class FollowerData {
        EntityId id;
        EntityId leader;
    }

    class FollowerContainer extends EntityContainer<FollowerData> {

        FollowerContainer(EntityData ed) {
            super(ed, Follow.class);
        }

        Stream<FollowerData> stream() {
            return Arrays.stream(getArray());
        }

        @Override
        protected FollowerData addObject(Entity entity) {
            FollowerData result = new FollowerData();
            result.id = entity.getId();
            result.leader = entity.get(Follow.class).getParent();
            return result;
        }

        @Override
        protected void updateObject(FollowerData t, Entity entity) {
        }

        @Override
        protected void removeObject(FollowerData t, Entity entity) {
        }
    }
}

Finally

You can extend this with an offset as at the moment the follower and the leader will have the same position, which might not be wished as you probably want to have the lamp, weapon, or tool in front of your character and not on the very same position. As well you could implement a smoothing when following something.

Thanks for reading. If you have questions, suggestions, or an oppinions leave a comment below.

ECS Pattern: Decay

This blog post is based on Entity Component System are Crazy Cool.
There are so many things in-game that have a lifetime. Bullets, effects, debris, blood, vanishing tiles in a can’t stop running-game, and many more things which have a lifetime.
In the past, I would have done it separately depending on which situation something hast to vanish. With the entity component system you can solve all of them with one component and one system. The decay component and decay system.

I use jMonkeyEngine with Zay-ES written in Java.

Component

Bullets, debris, blood are represented by entities with a certain set of components in our game world. A bullet entity for example has a model component, a position component, and a damage component. For the decay system, we need a decay component we can attach to those entities to make them disappear after a while. Instead of detecting where the bullet is, you simply remove the bullet after a while if it didn’t hit something. No need to detect where the bullet is right now, just remove it after let’s say a second.

public class Decay implements EntityComponent {

    public long timeout;

    public Decay(long timeoutMs) {
        this.timeout = timeoutMs;
    }

    public long getTimeoutMs() {
        return timeout;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "[" + timeout + " ms" + "]";
    }
}

On creation, you define the timeout for the decay component. The timeout in ms does define how long the entity shall live.

System

The decay system does the calculation if the entity’s lifetime has been reached. It doesn’t matter if it is a bullet, an effect, debris, or even the space station. And that is the shiny beauty of an entity component system. You can give something a lifetime in your game at any time. You can decide to add a lifetime to something even very late in the development process. You can decide this a day before you launch the game as it is simply a one-liner by adding a decay component to that entity. No refactoring or code moving involved at all.

Skeleton

Let’s start with a very basic system and set up everything we need, like the entity data and the decay container.

public class DecaySystem extends BaseAppState {

    private EntityData ed;
    private DecayContainer decayContainer;

    public DecaySystem() {
    }

    @Override
    protected void initialize(Application app) {
        Main main = (Main) app;
        ed = main.getStateManager().getState(EntityDataState.class).getEntityData();
    }

    @Override
    protected void cleanup(Application app) {
    }

    @Override
    protected void onEnable() {
        decayContainer = new DecayContainer();
        decayContainer.start();
    }

    @Override
    protected void onDisable() {
        decayContainer.stop();
        decayContainer = null;
    }

    @Override
    public void update(float tpf) {
            decayContainer.update();
        }

    private class DecayData {
    }

    private class DecayContainer extends EntityContainer<DecayData> {

        DecayContainer() {
            super(ed, Decay.class);
        }

        Stream<DecayData> stream() {
            return Arrays.stream(getArray());
        }

        @Override
        protected DecayData addObject(Entity entity) {
            DecayData data = new DecayData();
            return data;
        }

        @Override
        protected void updateObject(DecayData data, Entity entity) {
        }

        @Override
        protected void removeObject(DecayData data, Entity entity) {
        }
    }
}

It does nothing yet. We will now fill in the needed code. Which is not really a lot. Very simple.

Decay Entity Container

Let’s begin with the Zay-ES entity container to get all the added, removed, and updated entities with a decay component attached. In the addObject() method we create our local decay data to handle the timeout. I almost always have a local data representation with some additional logic. We store the entity id and the timeout in milliseconds. That’s it.
You can add as well logic for the updateObject() method to be able to update the decay of an entity during your gameplay, think of a plant that got some water or fertilizer or tool which got repaired.

    private class DecayContainer extends EntityContainer<DecayData> {

        DecayContainer() {
            super(ed, Decay.class);
        }

        Stream<DecayData> stream() {
            return Arrays.stream(getArray());
        }

        @Override
        protected DecayData addObject(Entity entity) {
            long timeoutMs = entity.get(Decay.class).getTimeoutMs;
            DecayData data = new DecayData(entity.getId(), timeoutMs);
            return data;
        }

        @Override
        protected void updateObject(DecayData data, Entity entity) {
                }

        @Override
        protected void removeObject(DecayData data, Entity entity) {
        }
    }

Local Decay Data

The local decay data class handles the timeout. We store the start time and the timeout and with getPercent() method we return the decay as a value 0 (no decay) and 1 (fully decayed). Very simple logic.

    private class DecayData {

        EntityId id;
        private long start;
        public long timeout;

        DecayData(EntityId eId, long timoutMs) {
            this.id = entity.getId();
            this.start = System.nanoTime();
            this.timeout = timeoutMs * 1000000;
        }

        double getPercent() {
            long time = System.nanoTime();
            return (double) (time - start) / timeout;
        }
    }

Update

And finally, in the update method, we loop over all decay data and remove those which are fully decayed.

    @Override
    public void update(float tpf) {
        decayContainer.update();
        decayContainer.stream().forEach(e -> {
            if (e.getPercent() >= 1.0) {
                    ed.removeEntity(e.id);
            }
        });
    }

Additionally

You can implement as well visualization systems to make the decay of a thing like a plant or a tool visible and give feedback to the player.

The End

That’s it. Thanks for reading. If you have suggestions or questions just write a comment below.

Entity Component System Is the Coolest Thing I Ever Met

Entity component system or short ECS is one of the coolest, brightest, and most beautiful paradigm in programming I have ever met. It is data-driven and different from object-oriented programming most people know nowadays. It is mainly used in game development. The entity component system approach brought me back the feeling of the old days hacking games on a zx81 with a 4kbyte ram extension.

The "All Fucked Up" game relays heavily on entity component system and makes it super cool to develop.

But What is ECS

Looking at the name we can identify three parts.

  • Entity
  • Component
  • System

Entity

An entity is just an identifier. Nothing more than that. In my case a number.

Component

An entity can have one or many components. A Component is just data, like the position or the model name or health. It has no functionality like walk, spell or any other activity. It might have getters. I use getters.

System

The System subscribes for entities with certain components and implements what should happen with added, updated or removed entities.

Basically, you subscribe for entities with a certain set of components, and in the update loop of your system, you get all the added, updated, and removed entities.

So let’s say you are interested in all entities which do have a position and a model component. Let’s further assume that there are already entities "1" and "2" with a position and a model component. In the current frame you add entity "3", update the position of entity "2" and remove entity "1". In the update loop, you get entity "3" as added, entity "2" as updated, and entity "1" as removed. Your system does now load and display the new entity "3" to the given position, move the entity "2" to the new position and removes entity "1" from the screen.

Note: The system in this example only sees the entities with a position and a model. If you remove either the position or the model from an entity, this entity will appear as removed in this example.

Let’s deep dive

I love code examples. My click experience was to use ECS for displaying the objects on the screen and move them around. I will provide some real code in a simplified form and explain the parts.

jMonkeyEngine and Zay-ES

I use jMonkeyEngine with Zay-ES written in Java. You might use another game engine and even another language, but that doesn’t really matter, as I’m sure you guys are all smart enough to make the link to your game engine as they don’t differ that much.

The System

First of all, I use app states as my Systems provided by the jMonkeEngine. All app states update method are called every frame in the order they are registered. This might look different for your game engine and maybe you even have to introduce a construct like this.

This app states here is the System to display the models on the screen.

public class ModelViewState extends BaseAppState {
    private Node modelRoot;
    private Main main;
    private EntityData ed;
    private ModelContainer modelContainer;

    @Override
    protected void initialize(Application app) {
        ...
    }

    @Override
    protected void onEnable() {
        ...
    }

    @Override
    protected void onDisable() {
            ...
        }

    @Override
    public void update(float tpf) {
            ...
        }

    private class ModelContainer extends EntityContainer<ModelData> {
        ...
    }
}

Lets add some flesh to this skeleton…

Initialization

In the initialization method I set up the model root, a pointer to the main app, and the entity data. The entity data is in my case an own app state, I like to organize the stuff in-app states, makes it clearer and the code gets less cluttered.

    @Override
    protected void initialize(Application app) {
        modelRoot = new Node();
        main = (Main) app;
        ed = main.getStateManager().getState(EntityDataState.class).getEntityData();
    }

Enable

The application state features an enable method, that might be different for your game engine. I use this to let the models appear by adding my model root node. It’s not really relevant but helps to understand the software a bit better. So no magic.

What is relevant is the model container we instantiate and start, this is an ECS container. The model container is described in all details further down.

    @Override
    protected void onEnable() {
        main.getRootNode().attachChild(modelRoot);
        modelContainer = new ModelContainer(ed);
        modelContainer.start();
    }

Disable

The application state also features a disable method. I use this to remove all the models by simply remove the model root from its parent. Very handy. It’s as well not really relevant to explain the ECS architecture.

The ECS model container is stopped and destroyed as well.

    @Override
    protected void onDisable() {
        modelContainer.stop();
        modelContainer = null;
        modelRoot.removeFromParent();
    }

Update

In the update method, we update the started model container. For this example this is it, nothing else is needed for the update loop. For more advanced stuff you need to iterate over all entities and for example calculate collision detection or other logic you may need to make entities interact with each other.

    @Override
    public void update(float tpf) {
        modelContainer.update();
    }

ECS Model Container

The ECS container from Zay-ES makes it really simple to handle added, removed and update entities on every update() call.

Data Class

I always define a data class, in this case, it is very simple and holds just the loaded spatial. That’s it.

   private class ModelData {
         Spatial model;
     }

The ECS Container

The ECS container does subscribe for all entities which have a ModelType and a Position component. This is now the important stuff. We are interested in entities that have a model and a position component.

    private class ModelContainer extends EntityContainer<ModelData> {

        public ModelContainer(EntityData ed) {
            super(ed, ModelType.class, Position.class);
        }

Add Entities

The addObject method is called for all new entities which do have a ModelType and a Position component. For every entity, I create a model data object and fill in the loaded model. Only the model name must be stored in the component and not the spatial itself. This leads to very decoupled software, you can even have another system that also is interested in the model and the position but does for example display it in a minimap. To store the spatial in the component would be an anti-pattern. I also call the updateObject method to place the added model. Of course to make it visible we have to attach the model to the model root.

        @Override
        protected ModelData addObject(Entity entity) {
                    modelData = new ModelData();
                    String modelName = entity.get(ModelType.class).getModelName();
                    modelData.model = main.getAssetManager().loadModel(model);
                    updateObject(modelData, entity);
                    modelRoot.attachChild(modelData.model);
                    return modelData;
                }

Update Entities

The updateObject method is called if either the ModelType or the Position of an entity has changed. In this example, I’m only interested in the position changes. A position holds the new location and the new rotation. So if your controller stated wants to move your hero around, it simply updates the position component of the hero entity.


        @Override
        protected void updateObject(ModelData modelData, Entity entity) {
                    Position position = entity.get(Position.class);
                    modelData.model.setLocalLocation(position.getLocation());
                    modelData.model.setLocalRotation(position.getFacing());
        }

Remove Entities

Finally, we have the removeObject method, which is simply plain to remove the models, because either the Position and/or the ModelType component was removed by another system, for example, your dead system.


        @Override
        protected void removeObject(ModelData modelData, Entity entity) {
                    modelData.removeFromParent();
        }
    }

Place Models and Move it

The code we have so fare wants entities with ModelType and Position components, so we need to place that. For this, I have a level app state which places the initial stuff including my hero. The initial stuff is done in the app state enable method, where I load the level or build up the level, that depends. Ok real quick

public class ModelViewState extends BaseAppState {
    private Main main;
    private EntityData ed;
    private EntityId myHero;
    ...

    @Override
    protected void onEnable() {
            myHero = ed.createEntity();
        ed.setComponents(myHero, new ModelType("MyFancyModel.j3o"), new Position(new Vector3f(0, 0, 0)));
    }

    @Override
    public void update(float tpf) {
        ed.setComponent(myHero, newPosition(newVector3f(tpf, 0, 0)));
    }
        ...
}

Yes that simple, this moves the object to the right in my case with a speed of 1 unit per second. And java is pretty good with very short-living objects and never was an issue for me. I have up to 2500 or more frames per second if I do not run it in sync mode. And even with a lot, and I mean a lot of entities (up to 10’000 objects) it is not an issue…
And right the position component is a new instance everytime you change it, java seems to be smart and efficient enought to handle short living objects.

The wow moment

Just to displaying and moving the stuff around wasn’t really my wow moment, it was just the now-I-understand moment. It’s even like why should I use ECS for this? What is the benefit? The real wow moment was the decay system for me. It is a pattern you probably have in every game.

What is a decay system exactly? The decay system is interested in all entities with the Decay component, which basically says how long this entity shall live. Very handy to clean stuff up like bullets, which are probably very short living in almost all games. And you have tons of them and as well different kinds of them. But as well any entity which is dying or has to be removed after a while. You even can display the decay state with another system that is also interested in the decay component. The only thing you have to do is to attach the Decay component to the entity which should vanish after a while. No inheritance, no direct component linking, just attach the Decay component.

You can also think of a health system to give something health and it doesn’t matter if that is a dog, a tree, a house, a stone, or your hero. And you can add it anytime. Maybe you started with stones without health, but then your game designer shows up and wants that the stones have health and the hero can destruct them with a tool. No big deal it is a one-line addition by just adding Health component to the stone entity and it has health. If you have already a health visual system in place the health of the stones will be displayed like any other thing with health. And that’s really cool.

If you made it this far

Put your questions and suggestions in the comments below. Thanks for reading.