I am making my first simple game engine and decided to go with a ECS (Entity component system) from inspiration from Unity.
I spent quite awhile online trying to figure out how to implement it. I found nothing and had to write my own.
However, i quickly ran into a problem: Cross component communication. Lets say i had a component that needed access to the physics component to change its velocity. That is what i need to be able to do.
Here is the code, and what i have tried:
ENTITY CLASS (Simplified)
public abstract class GameObject {
private List<Component> comp = new ArrayList<Component>();
public void Update() throws Exception{}
public void Render(Graphics g) throws Exception{}
public void CompUpdate(){
for(int i=0; i<comp.size(); i++){
comp.get(i).Update(this);
}
}
public void CompRender(Graphics g){
for(int i=0; i<comp.size(); i++){
comp.get(i).Render(this,g);
}
}
public void addComp(Component comp){
if(hasComp(comp.getClass())){return;}
this.comp.add(comp);
}
public Component getComp(Class<? extends Component> comp){
for(int i=0; i<this.comp.size(); i++){
if(this.comp.get(i).getClass() == comp){
return this.comp.get(i);
}
}
return null;
}
public boolean hasComp(Class<? extends Component> comp){
for(int i=0; i<this.comp.size(); i++){
if(this.comp.get(i).getClass() == comp){
return true;
}
}
return false;
}
}
COMPONENT
public class BoxRender extends Component{
@Override
public void Update(GameObject obj){
Component comp = obj.getComp(engine.components.ImageRender.class);
//This is the problem here. getComp doesnt return the comp i need.
//This is what i need to do
Image image = comp.getImage(); //ImageRender has a getImage() method. I need to be able to get that.
image.blahblah(); //Example
}
}
QUESTION
So how can i have my components communicate? Do i have to rewrite my system? -Thanks