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

2016/5/14

Need help with spawning in actors

Hydrowarrior Hydrowarrior

2016/5/14

#
Basically what I want to do is check an area in my world, if that area does not have an wall already in it, it will spawn a dot. PrepX and PrepY = 0. My world is 21 x 21. PrepX and PrepY are the coordinates of the tile I am trying to check. The following code runs in my constructor method in my world class:
public void makeDots()
    {
        for(int TimesRan = 0; TimesRan < 441; TimesRan++){
            PrepX++;
            if(PrepX == 21){PrepX = 0; PrepY++;}
            List w = (List)getObjectsAt(PrepX,PrepY,Wall.class); 
            if(w == null) {addObject(new Dot(), PrepX,PrepY);} 
            
        }
What happens is that it doesnt spawn any dots. If I change (w ==null) to (w!=null), it spawns dots everywhere, including underneath the walls which is what I do not want, I have no clue why it even spawns the dots, im not very familiar with lists. What am I doing wrong?
danpost danpost

2016/5/14

#
The problem is that a List object is always returned when you use the 'getObjects' or 'getObjectsAt' method -- these methods never return 'null'. So, the check you should be using is whether the list has a size of zero or not (or whether the list is empty or not empty):
if (w.isEmpty()) ... 
danpost danpost

2016/5/14

#
There is no need to have 'PrepX' and 'PrepY' retained for the life of the world. You can change the method to this:
public void makeDots()
{
    for (int y=0; y<21; y++) {
        for (int x=0; x<21; x++) {
            if (getObjectsAt(x, y, Wall.class).isEmpty()) {
                addObject(new Dot(), x, y);
            } 
        }
    }
}
and remove'PrepX' and 'PrepY' totally from the class.
You need to login to post a reply.