This is Part 2. Here’s Part 1 of the series.
The Magical World of Entities and Components
Hello and welcome back for the next iteration in this ECS adventure. You’ll learn about how I chose to make components, tied to the same entity, talk together. I believe this is the coolest part.
- Your game.
Hah. That’s it.
And now, let’s dive into a…
Let’s imagine we have a game where there are WOODEN CRATES, and WOODEN DOORS. That means we have two entities, the Crate entity, and the Door entity. Also, wood can break, and wood can burn. These are two components.
- Wooden Crate
- Wooden Door
It lends itself pretty well to our system. Let’s see what are our components’ outstanding traits:
Properties - isBroken - bool - healthPoints - number Events - onBroken Methods - hurt(damage) - break()
Properties - isBurnt - bool - isBurning - bool - burnPoints - number (like health points, removed by burning) Events - onBurnt Methods - burn() - burnt()
This is totally BAREBONES, we could add a lot more properties and methods for the sake of making this even more interesting, but this is a bit out of the scope of this tutorial, and in time you’ll be able to do it yourself.
ALRIGHT! Remember our part 1 on Entity Component System? We’ll continue with what we learned on that tutorial. Let’s take a look at what our components look like in a file.
[snippet id=”83″ title=”ECS – part 2, Breakable” height=”0″ line_numbers=”true”]
[snippet id=”87″ title=”ECS – part 2, Flammable” height=”0″ line_numbers=”true”]
So do you see how the only thing in these components is just handling something VERY specific? They are ZERO aware of the door, and of any other components. They are blind.
But you ask…
– you say, clearly flustered, your fists ready to fight –
“If the components are not aware of each other, how can the flames break the entity?”
Excellent question! The glue resides on the entity. BEHOLD!
[snippet id=”95″ title=”ECS – part 2, Door entity creation” height=”0″ line_numbers=”true”]
So as you can see, communication between components is as easy as
masterComponent.signal.add ( slaveComponent.method, this );
Now that we have our glue, our components and our entities, it’s easy to tie them all together. Here’s the complete file for a simple Door.
[snippet id=”91″ title=”ECS – part 2, Door entity” height=”0″ line_numbers=”true”]
Now, your Door only needs to catch fire to start its terrible non-zen journey into destruction.
[snippet id=”97″ title=”ECS – part 2, Door catching fire” height=”0″ line_numbers=”true”]
And voilà! FIRE! DESTRUCTION! PAIN! TERRIBLE THINGS!
All of this with components 😀
Thank you for reading, and don’t hesitate to comment and share!