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

2014/5/23

Find number of actors and add one if there are none.

Arichman Arichman

2014/5/23

#
I have an actor called Red_Ball getting removed by an actor called "Red_Goal". I want a function that checks to see how many red balls there are and adds one if there are none.
danpost danpost

2014/5/23

#
What have you tried? What methods do you think you might need to use?
Arichman Arichman

2014/5/28

#
I think I need to use the getObject() and addObject(). I tried using them but I couldn't find a good example of usage.
Arichman Arichman

2014/5/28

#
I looked around a little more and a lot better and found some stuff. I couldn't quite discern how to do this so help would be appreciated.
danpost danpost

2014/5/29

#
Well, you did find some World class methods, so I will presume you want the code in your World subclass (which is where it probably should go). 'getObjects' will return a List object containing elements of the given type that are in the world. You basically want to know the number of elements that are returned in the list; or more simply, you want to know if the list is empty or not. Looking at the List class API, you will find both a 'size' and an 'isEmpty' method. So you could ask if the size of the list is zero or you could ask if the list is empty. Either way, you will use 'addObject' to add a new one into the world if none were in the world.
Arichman Arichman

2014/5/29

#
I did this
public void spawnBall()
    {
       List<Red_Ball> numredball = getObjects(Red_Ball.class);
       if (numredball.isEmpty())
       {
           Red_Ball red_ball = new Red_Ball();
           addObject(red_ball, 224, 255);
       }
    }
I don't get a compiler error but I don't get a new ball either. I took the ball spawn code directly from the prepare() so I know that is correct. what am I doing incorrectly?
davmac davmac

2014/5/29

#
You have written a 'spawnBall()' method and it looks ok, but are you actually calling it from your act method?
Arichman Arichman

2014/6/2

#
its in my world subclass, should it not be there?
Arichman Arichman

2014/6/2

#
I put it in the red ball class and got this error cannot find symbol- method getObjects(java.lang.Class<Red_Ball>) where should it go?
davmac davmac

2014/6/2

#
its in my world subclass, should it not be there?
It's fine that it's in your world subclass, but does it ever get called? I.e. Have you got an act() method in your world subclass which calls the spawnBall() method?
Arichman Arichman

2014/6/2

#
I have it in the thing with the super() and the prepare(). But now its in the right place, thanks :)
You need to login to post a reply.