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

2013/10/15

Add objects randomly at same X' Y' coordinate

13111876 13111876

2013/10/15

#
Hello, I'm building a game and i'm trying to get certain objects to spawn randomly on specific X and Y coordinate. I also want that each object appears after ten seconds on the specific coordinate. Can someone help me with this. Thanks in advance.
Gevater_Tod4711 Gevater_Tod4711

2013/10/15

#
To make objects randomly spawn you can use the Greenfoot.getRandomNumber(int) method. To make them spawn after a certain time you need a counter variable. Add this code to your world method:
private int spawnCounter = 0;

public void act() {
    if (spawnCounter > 100) {
        spawnCounter = 0;
        addObject(new YourObject(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
    }
    spawnCounter++;
}
I'm not shure whether 100 (line 4) is about 10 seconds. You'll have to try.
13111876 13111876

2013/10/15

#
@Gevater_Tod47111 thank you very much, this works! The only thing is that the object is appearing everywhere in the world. I want the object to appear each time at these coordinate X=141, Y=211.
Gevater_Tod4711 Gevater_Tod4711

2013/10/15

#
Oh sorry then I mussunderstood you. I thought you meant the objects should spawn at a random position. If you want them to spawn at (141|211) you need to change line 6 of the code to: addObject(new YourObject(), 141, 211);
danpost danpost

2013/10/15

#
On line 4, use some number around 500 to 600. On line 6, replace the random numbers with your coordinates.
13111876 13111876

2013/10/15

#
@ Gevater_Tod4711 Thank you very much, this was very helpful.
13111876 13111876

2013/10/15

#
@danpost Yes, thank you!
nico_vo nico_vo

2016/1/21

#
How can I do things spawn randomly, but only at the top edge (at the top of the y axis, but just along the x axis)?
addObject(new YourObject(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
with this, objects spawn randomly, so I guess I have to put some value between the brackets of the getHeight() part, at the end of the code line. the thing is, that I don't know what value should that be. ): thanks in advance :)
danpost danpost

2016/1/22

#
The top edge of the screen is where the y-coordinate value is zero. Therefore: addObject(new YourObject(), Greenfoot.getRandomNumber(getWidth()), 0);
You need to login to post a reply.