This site requires JavaScript, please enable it in your browser!
Greenfoot back
bennordin21
bennordin21 wrote ...

2015/7/2

How can i access all objects of a class from another?

bennordin21 bennordin21

2015/7/2

#
LineVert linevert = (LineVert)(getWorld().getObjects(LineVert.class)).get(0);
This is the code used to get access to the first object of its class in the scenario, but what I want is access to all of them so that I can control all of them.
public class Dot extends Actor
{
    public boolean turn;
    public Dot()
    {
        turn = true;
    }

    public void act() 
    {
        LineVert linevert = (LineVert)(getWorld().getObjects(LineVert.class)).get(0);
        LineHorz linehorz = (LineHorz)(getWorld().getObjects(LineHorz.class)).get(0);
        if(Greenfoot.mouseClicked(linevert))
        {
            if(turn)
            {
                linevert.setImage("Line.png");
                turn = false;
            }
            if(!turn)
            {
                linevert.setImage("Line6.png");
                turn = true;
            }

        }
        if(Greenfoot.mouseClicked(linehorz))
        {
            if(turn)
            {
            linehorz.setImage("Line3.png");
            turn = false;
        }
        if(!turn)
        {
            linehorz.setImage("Line5.png");
            turn = true;
        }
        }

    }    
}
fejfo fejfo

2015/7/2

#
I don't really get what you want but I thing you want to cycle trough all the Objects of LineVert and LineHorz. you could do that with an enhaced forloop like this :
Import java.util.List;
public class Dot extends Actor
{
    public boolean turn;
    public Dot()
    {
        turn = true;
    }
 
    public void act() 
    {
        List<LineVert> lineverts = (List<LineVert>)(getWorld().getObjects(LineVert.class));
        List<LineHorz> linehorzs = (List<LineHorz>)(getWorld().getObjects(LineHorz.class));
        for(LineVert lv : lineverts) {       
                if(Greenfoot.mouseClicked(lv))
                {
                    if(turn)
                    {
                        lv.setImage("Line.png");
                        turn = false;
                    }
                    if(!turn)
                    {
                        lv.setImage("Line6.png");
                        turn = true;
                    }
 
                }
        }
        for(LineHorzs lh : linehorzs) {
                if(Greenfoot.mouseClicked(lh))
                {
                    if(turn)
                    {
                            lh.setImage("Line3.png");
                            turn = false;
                }
                        if(!turn)
                        {
                            lh.setImage("Line5.png");
                            turn = true;
                }
        }
 }
 
    }    
}
bennordin21 bennordin21

2015/7/2

#
Thank you that worked
You need to login to post a reply.