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

2013/1/19

How do you add an object to the world only once?

Cross Cross

2013/1/19

#
I have a Shark class, and for Big fish Small fish, I want the shark to spawn once when the score reaches 1500. I tried this:
public void spawnShark()
    {
        if (points == 1500)
        {
            addObject(new Shark(), 400, 400);
        }
    }
But when I reached to 1500 points, the sharks continued to be added into the world. Is there a way I could fix that?
moobe moobe

2013/1/19

#
This is easy, look at this code:
private int sharkAdded = false; //declare a boolean variable
public void spawnShark()  
    {  
        if (points == 1500 && sharkAdded == false)  
        {  
            addObject(new Shark(), 400, 400);  
            sharkAdded = true;
        }  
    } 
This should solve your problem :)
danpost danpost

2013/1/19

#
Or (without the variable)
public void spawnShark()
{
    if(points == 1500 && getObjects(Shark.class).isEmpty()) addObject(new Shark(), 400, 400);
}
Later, if you wanted to add another at maybe 3000 points:
if(points==3000 && getObjects(Shark.class).size()<2) addObject(new Shark(), 400, 400);
Cross Cross

2013/1/19

#
Awesome. Thank you guys so much.
You need to login to post a reply.