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

2021/3/22

Spawning an Object between Two Points

Dave2222 Dave2222

2021/3/22

#
Hi all! I am working on a project and ran into a predicament. I need my object (Player1) to spawn into the world. It needs to spawn at one point or another at random when I click the reset button. I keep messing up, so I was wondering if anyone could give me some guidance. I tried using the OR (||), but it does not seem to be working.
private void prepare()
    {
         Player Player1 = new Player(); 
         addObject (Player1, 165,100 || 159, 425);
    }
rocket770 rocket770

2021/3/22

#
private void prepare()
    {
        int x = 0, y= 0;
        int rand=Greenfoot.getRandomNumber(1); 
        if(rand == 0) { 
            x = 165;
            y = 100;
        } else {
            x = 159;
            y = 425;
        }
         Player Player1 = new Player(); 
         addObject (Player1, x,y);
    }
danpost danpost

2021/3/22

#
Line 4 would preclude the else coordinates from ever being set. The argument for getRandomNumber gives the number of possible outcomes. Use:
int rand = Greenfoot.getRandomNumber(2);
to make a 2-way choice. It will now return either zero or one.
Dave2222 Dave2222

2021/3/22

#
Thank you! Both of your responses have helped me!
rocket770 rocket770

2021/3/23

#
Oops, yeah miss-typed that one.
You need to login to post a reply.