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

2018/11/26

How do I spawn objects at random locations without risking that they spawn into each other?

DML DML

2018/11/26

#
For better understanding, here´s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public void prepare()
    {
        int wX = Greenfoot.getRandomNumber(17)+1;
        int wY = Greenfoot.getRandomNumber(17)+1;
        int sX = Greenfoot.getRandomNumber(17)+1;
        int sY = Greenfoot.getRandomNumber(17)+1;
        Wand wand = new Wand();
        int wandX = wand.getX();
        int wandY = wand.getY();
        Schatz schatz = new Schatz();
        int schatzX = schatz.getX();
        int schatzY = schatz.getY();
        Abenteurer abenteurer = new Abenteurer();
        addObject(abenteurer, 3, 8);
        Waechter waechter = new Waechter();
        addObject(waechter, 9, 8);
        for (int i = 0; i < 25; i++)
        {
            if (wX != wandX && wY != wandY)
            {
                this.addObject (wand, Greenfoot.getRandomNumber(17)+1, Greenfoot.getRandomNumber(17)+1);
            }
        }
        for (int i = 0; i < 10; i++)
        {
            if (sX != schatzX && sY != schatzY)
            {
                this.addObject (schatz, Greenfoot.getRandomNumber(17)+1, Greenfoot.getRandomNumber(17)+1);
            }
        }
    }
In lines 3-12, I defined some stuff that I need for the if-expressions that come later, but unfortunately, I can´t use getX or getY as the objects haven´t been added to the world yet. Adding the content of lines 3-12 into the if-expression would be too late because I need schatzX, schatzY, wandX and wandY for starting the if-expressions in the first place. Do you have any ideas how to fix this problem?
danpost danpost

2018/11/26

#
DML wrote...
<< Code Omitted >> In lines 3-12, I defined some stuff that I need for the if-expressions that come later, but unfortunately, I can´t use getX or getY as the objects haven´t been added to the world yet. Adding the content of lines 3-12 into the if-expression would be too late because I need schatzX, schatzY, wandX and wandY for starting the if-expressions in the first place. Do you have any ideas how to fix this problem?
If this is a grid world (cell size not pixel-sized), then you could just make use of the getObjectsAt method as you add the actors into the world.
You need to login to post a reply.