ECS Component
What's a component ?
In our game Engine, a component is a data structure that holds specific attributes related to an entity.
Components are pure data; they do not contain any logic or behavior.
Examples of components:
PositionComponent: Holds x, y coordinates (and possibly z for 3D).
VelocityComponent: Contains speed and direction.
HealthComponent: Keeps track of the entity's health points.
SpriteComponent: Holds information related to rendering, like texture or sprite sheet data.
How to write one ?
In our game Engine, we let possibility for developers and community to write their own components. Components are written in C++.
Tutorial:
In this tutorial, we'll create a Velocity component.
First, create a new file named VelocityComponent.hpp. Include the IComponent header file located in the Server/include/ folder:
#include "Server/include/IComponent.hpp"Then create your component class. This class must inherit from the IComponent class.
#include "Server/include/IComponent.hpp"
class Velocity : public IComponent
{
};You must create the getType( ) method because of the pure virtual method of IComponent. This method will be used by Systems to cast your Component by its type.
Be careful, your type must be unique. In case of other Component with the same type name, one of both will be overridden.
#include "Server/include/IComponent.hpp"
class Velocity : public IComponent
{
public:
const std::string &getType() //Must be implemented to override the pure virtual method of IComponent
{
return _type;
};
private:
std::string _type = "Velocity";
};Then create your constructor with all data you want.
For example, in a velocity class, we need an x and y value. To do so:
#include "Server/include/IComponent.hpp"
class Velocity : public IComponent
{
public:
float x = 0.0f; // velocity x
float y = 0.0f; // velocity y
Velocity(float x = 0.0f, float y = 0.0f) : x(x), y(y) {} // Constructor of our Velocity component
const std::string &getType()
{
return _type;
};
private:
std::string _type = "Velocity"; // Type of our Component
};That's it ! You created your first component, but now how to use it in our game Engine ?
This is pretty simple.
Create a cpp file and put this inside:
#include "VelocityComponent.hpp"
extern "C" IComponent* loadComponentInstance() {
return new Velocity();
}Here the content:
You included your hpp file previously created with your component.
Then the loadComponentInstance is the main function of your Component. When the game Engine will open your component, it's going to call the loadComponentInstance() function to get your Velocity. So be careful, loadComponentInstance is very IMPORTANT!
Compile your component thanks to this command in your terminal:
g++ -fPIC -shared -o theNameOfYourComponent.so yourFile.cppYou created a file name theNameOfYourComponent.so, to use it in the game Engine, you just have to put this file in the Server/lib/components/ folder.
The Game Engine will automatically open your file when running.