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

2019/3/27

Randomly spawning objects in set locations at the start of the game

EthanWasHere_ EthanWasHere_

2019/3/27

#
Hi all, Basically I have this trip wire in my game and I would like at the start of every time the game starts that it spawns 2 trip wires in random set locations. But i'm not sure how I could do it, any advice?
danpost danpost

2019/3/27

#
EthanWasHere_ wrote...
I have this trip wire in my game and I would like at the start of every time the game starts that it spawns 2 trip wires in random set locations. But i'm not sure how I could do it, any advice?
Give range or values at which trip wire can be spawned. Show some attempted code. Your post is unsupported and ambiguous.
EthanWasHere_ EthanWasHere_

2019/3/28

#
I would like it to spawn at either 125, 380 or 885, 381, but currently I am just spawning it in the world using:
addObject( new Trip_Wire,  125, 380 );
Super_Hippo Super_Hippo

2019/3/28

#
if (Greenfoot.getRandomNumber(2)==0) addObject(new Trip_Wire(), 125, 380);
else addObject(new Trip_Wire(), 885, 381);
Or, if you are planning to add more:
private int[] locX = {125, 885},
              locY = {885, 381};

//…

int r = Greenfoot.getRandomNumber(locX.length);
addObject(new Trip_Wire(), locX[r], locY[r]);
or
private int[][] loc =
{
    {125, 380},
    {885, 381}
};

//…

int r = Greenfoot.getRandomNumber(loc.length);
addObject(new Trip_Wire(), loc[r][0], loc[r][1]);
EthanWasHere_ EthanWasHere_

2019/3/28

#
Thanks, for helping except now I get the error "Illegal start of expression" with the code:
 {
        private int[][] loc =
   {
    {125, 380},
    {885, 381}
   };
   int r = Greenfoot.getRandomNumber(loc.length);
   addObject(new Trip_Wire(), loc[r][0], loc[r][1]);
   }
how would I go about fixing it?
danpost danpost

2019/3/28

#
EthanWasHere_ wrote...
Thanks, for helping except now I get the error "Illegal start of expression" with the code: << Code Omitted >> how would I go about fixing it?
Remove the word "private".
EthanWasHere_ EthanWasHere_

2019/3/29

#
Cheers!
You need to login to post a reply.