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

2014/1/4

How to define a range of coordinates?

DSP512 DSP512

2014/1/4

#
Hi everybody, I'm pretty new in Greenfoot and have a little problem. I want to randomly create objects in the world. To do this, I used this code in the World class:
public void randomSpawn() {
addObject (new Object(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
}
The Act-method used then this code:
public void act() {
randomSpawn();
}
Now I need a code that would let the objects spawn not over the whole world, but only over a smaller range, i.e. between x=100 and x=500, or from x=100 to the right edge.
bourne bourne

2014/1/4

#
Note: getRandomNumber(int limit) Returns a random number between 0 (inclusive) and limit (exclusive). So the limit is the number of possible values. All you have to do then is add an offset to change the beginning of range of values you can produce. Example: 100 + getRandomNumber(50) // Provides range
DSP512 DSP512

2014/1/4

#
Another question: How can I limit the random generation of objects, so only a certain number of objects is created? Thats because after several seconds, the whole world is completely filled with them. The other problem is that the objects are continuously generated and I need all objects to be created at the moment where the simulation starts.
bourne bourne

2014/1/4

#
Call the randomSpawn method in the World's constructor a number of times (instead of in the act method which is executed continuously as the scenario runs) You can use a for loop to create a block of code that is ran a number of times: for (int i = 0; i < 5; i++) // This will run the following block 5 times { }
You need to login to post a reply.