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

2019/2/20

I want to spawn a random object with conditions

Schrank Schrank

2019/2/20

#
Hello there, I want to spawn a new actor random in my World. But i dont want it to spawn on another actor. I know how to spawn it random anywhere. But how can I exclude it to spawn on the moving object. It can be randomly everywhere in the World.
1
2
3
public void addApple(){
        addObject(new Apple(),Greenfoot.getRandomNumber(17),Greenfoot.getRandomNumber(15));
    }
Fabo0815 Fabo0815

2019/2/20

#
If you don't want to spawn a Apple on an Actor, try this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
public void addApple() {
 
        Apple apple = new Apple();
 
        addObject(apple, Greenfoot.getRandomNumber(17), Greenfoot.getRandomNumber(15));
 
        if (apple.isTouching(Actor.class)) {
 
                Greenfoot.removeObject(apple);
                addApple();
 
        }
    }
Proprogrammer04 Proprogrammer04

2019/2/22

#
And if you want to make sure, that your other Actor can't interact with the apple Actor, you can use this:
1
2
3
4
protected void addedToWorld(World world)
{
        addApple(); /*the method of Fabo0815*/
}
danpost danpost

2019/2/22

#
Proprogrammer04 wrote...
And if you want to make sure, that your other Actor can't interact with the apple Actor, you can use this: << Code Omitted >>
Couple of this wrong with this. First, the addApple method would be in a World subclass where you cannot use the addedToWorld method. Secondly, if this was in another class other than Apple, you would be adding an apple instead of what type object this class creates (which is what would be wanted -- not an apple). The method given by Fabo0815 is a fine example of recursive method calling provided that an apple will always have some place to legally spawn without touching another actor. I was somewhat impressed when I first saw it. Nice one , Fabio0815; however, a simple while loop would have sufficed (no need to build up the stack by multiple calls here).
You need to login to post a reply.