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

2013/10/22

remove object and add a new on mouseclicked

vbh vbh

2013/10/22

#
i have a fish object that i want to remove and then add a new fish object when i clik the object whit the mouse i have tryed different ways but cant work it out so ill be glad if someone culd help me out :-)
Gevater_Tod4711 Gevater_Tod4711

2013/10/22

#
If I understood you correctly you want to remove your fish if you click on it and add a new one. To do this you need to check whether the fish was clicked like this:
//in your fish class;
public void act() {
    if (Greenfoot.mouseClicked(this)) {
        getWorld().addObject(new Fish(), Greenfoot.getRandomNumber(getWorld().getWidth()), Greenfoot.getRandomNumber(getWorld().getHeight()));//add a new fish at a random position;
        getWorld().removeObject(this);
        return;
    }
}
vbh vbh

2013/10/22

#
Thank you very much :-)
vbh vbh

2013/10/22

#
Hi again the code above does the trick whit removing and adding a new object, but sometimes the new fish object isnt showing in world any suggestion to way??? i have tryed to change the code to public void act() { if (Greenfoot.mouseClicked(this)) { getWorld().addObject(new Fish(), Greenfoot.getRandomNumber(500)<10), Greenfoot.getRandomNumber(400)<10); getWorld().removeObject(this); return; } } in hope that it would secure that the object is inside the world but i get an erro
davmac davmac

2013/10/22

#
Please use code tags for code in messages. You have:
getWorld().addObject(new Fish(), Greenfoot.getRandomNumber(500)<10), Greenfoot.getRandomNumber(400)<10);
What is the '< 10' for? (It is what is causing the error).
danpost danpost

2013/10/22

#
If the width of your world is 500 and you do not want to spawn within 10 of either side, then the range of x for spawning will be 480 (500 - 10 - 10 . This range value is what you should use as the 'getRandomNumber' argument; and since the first x allowable is at 10, just add that to the number returned from the random call.
int x = Greenfoot.getRandomNumber(480)+10;
It would be similar for the y coordinate.
vbh vbh

2013/10/29

#
Ty All its working now :-)
You need to login to post a reply.