Hello, I’m trying to create a simple entity/component system for a game and I’m having trouble getting components to interact. Say I have an entity which has a position component and a render component. How would I be able to get the render component to receive where to render it from the position component? Both components have a entity reference to their owner. Can anybody help me out with this?
To interact, put all entities into a class with List or what, usually a class that hold game logic. That class, should have access to render component, which to put it simple in java2d is Graphics object. Now every loop/tick, let all entity render them self through method inside them that receive render component parameter and use it along with position component.
And creating another class to hold position value is kinda overkill, just let entity class to have instance of Point2D or integers.
Well if I was to have components stored in an ArrayList in the entity, how would I be able to access them from that?
In the render component:
owner.entitiesList.?
Each component has a unique index string, could I access it through that?
//you get Graphics object 'g' from JPanel, BufferedImage or Canvas
for (int i=0; i<entitiesList.size(); i++){
entitiesList.get(i).render(g);
}
Thanks for your help but I have sorted this out. I created a method that will go through the list and get the needed component. Your method would of worked but I didn’t have a render method for each component. Here is mine:
[quote]but I didn’t have a render method for each component
[/quote]
then create it
I don’t know how many components you have in your list typically, but could you do this in as a HashMap and then just say
public Component getComponent(String index) {
return components.get(index);
}
I do it like this:
public <T> T getComponent(Class<T> type) {
for (Component comp : this) {
if (type.isAssignableFrom(comp.getClass())) {
return (T) comp;
}
}
return null;
}
Then you can write code like:
Renderer renderer = entity.getComponent(Renderer.class);
Do it like this so you won’t need to cast and get warnings:
public <T extends Component> T getComponent(Class<T> type) {
for (Component comp : this) {
if (type.isAssignableFrom(comp.getClass())) {
return comp;
}
}
return null;
}