Skip to content

Components

lucasstarsz edited this page Feb 22, 2021 · 3 revisions

Components

Components are another integral part of Slope -- they allow you to give entities data that define what the entity is, and what that entity has.

However, working with components is slightly more difficult. In order to add a component to an entity, you need to first add the component's class to the World object we created earlier.

Why? In short, this is to notify the World to allocate a component array for the component class. This is what enables components of that class to be added to the World -- and as a result, to entities.

Now that we've gone through the theory, let's get to code implementation. A component in Slope must implement the IComponent interface:

public class Position implements IComponent {
    public int x;
    public int y;
}

In order to use it, the component must then be registered in the World:

world.registerComponent(Position.class);

With that, we can add, get, or remove the component from our entity freely!

Position positionComponent = new Position();
// add component to entity
world.addComponent(entity, positionComponent);
// get component from entity
Position posComponent = world.getComponent(entity, Position.class);
// remove component
world.removeComponent(entity, Position.class);
// destroying the entity removes the component auto-magically
  • Do note that trying to get a component that an entity doesn't have will cause the World to crash.
    world.removeComponent(entity, Position.class);
    
    // Causes IllegalStateException
    Position posComponent = world.getComponent(entity, Position.class);

You might be wondering about that IComponent interface, and why I'm not following normal rules for Java classes for our Position class. Well...

The IComponent Interface

The IComponent interface, as is specified in its documentation, groups all components under one branch, allowing for generics to work as intended. It does not contain any code -- it is purely to unite all components under one roof.

Secondly, components need to follow the rules of Plain Old Data structures, or PODs. While it is not completely possible to achieve PODs in Java 15, it is possible to mimic them.

In short, components in Slope must follow these rules:

  • Implement the IComponent interface
  • Follow POD structure
    • All members must be public, and not static
    • No user-defined constructors
    • No user-defined methods

Beyond that, you're free to do as you wish with components.