Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
    
Messaging is the typical approach to this. You'll find a number of questions about the topic on the site. – Byte56 Feb 17 '15 at 23:32
    
@Byte56, thank you, but a quick search on this site, and on Google returned nothing (Of value/how to do). How would i do this? Any links? – Matt Feb 17 '15 at 23:44
    
    
There are lots of articles floating around (and several implementations in java), most notably Adam Martin's series: t-machine.org/index.php/2007/09/03/… – junkdog Feb 22 '15 at 23:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.