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

2013/4/5

Adding objects

Kiara Kiara

2013/4/5

#
Hey. I have a spider in the game, and I want to add one in a random place every time it dies and on random occasions. The code looks like this. public boolean die() { if (Greenfoot.mouseClicked(this)) { getWorld().removeObject(this); return true; } else { return false; } } public void repopulate() { if(die()) { getWorld().addObject(this, Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400)); } if(Greenfoot.getRandomNumber(10) < 10) { getWorld().addObject(this,Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400)); } } } I get a null pointer exception!
I wouldn't have code for a new spider in the Spider class. I would add it to the World. Have a repopulate() method in the world, that puts a new Spider in IF the spider is dead (which you can test with the die() method you have there.
Kiara Kiara

2013/4/5

#
Can you show me what that would look like @FlyingRabidUnicornPig ?
sure Here's your Spider object:
public class Spider extends Actor
{
    private boolean isDead = false;

    public void act()
    {
        if(Greenfoot.mouseClicked(this)
            die();
    }

    public boolean dead()
    {
        return isDead;
    }

    public void die()
    {
        isDead = true;
    }
}
Here's Your world:
public class WorldName extends World
{
    private Spider s = new Spider();

    public WorldName()
    {
        addObject(s, /* x and y */);
    }

    public void act()
    {
        if (s.dead())
            killSpider();
    }

    public void killSpider()
    {
        removeObject(s);
        addObject(s, /* x and y */);
    }
}
Hoped that helped.
Kiara Kiara

2013/4/5

#
Thank you so much!!!
No problem. :)
danpost danpost

2013/4/5

#
@FlyingRabidUnicornPig, that may not do what Kiara wants. With that, There will never be more than one spider and having a reference to one Spider object in the world class will not work when there is more than one in the world. Better, would be just for Kiara to use the code that he has, with one addition (referencing the world):
public void repopulate()
{
    WorldName world = (WorldName)getWorld();  // use your world class name
    if (die())
    {
        world.addObject(this, Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400));
    }
    if(Greenfoot.getRandomNumber(10) < 10)
    {
        world.addObject(this,Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400));
     }
}
This step is needed because once 'die' removes the spider from the world, 'getWorld' will return 'null' (hence, the nullPointerException).
You need to login to post a reply.