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

2013/10/22

Help spawning object

1
2
Baenefin Baenefin

2013/10/28

#
Ok I am going to do it a different way. What I would like is a shroom that spawns on certain random x coord. I would like it to spawn levelwide, but not say between, x coords 50-100 AND NOT between xcoord 500-600. How would I go by that?
danpost danpost

2013/10/28

#
Allowable possible x-coordinates amount to 'getWidth()-(100-50)-(600-500)' or 'getWidth()-150'.
1
2
3
int x = getRandomNumber(getWidth()-150);
if (x > 50) x += 50;
if (x > 500) x += 100;
The code above makes the proper adjustments to the coordinate value.
Baenefin Baenefin

2013/10/28

#
Thanks :). So If i get it correctly a given Shroom will not spawn between 1200-1088, 352-282 or 896-640
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void add(int addAmt) 
    
        ScoreCounter+=addAmt;   
        updateImage();
        int x = (Greenfoot.getRandomNumber(getWorld().getWidth()-(1200-1088)-(352-282)-(896-640)));
        if (x > 1088) x += 112;
        if (x > 282) x += 70;
        if (x > 640) x += 256;
        int y = Greenfoot.getRandomNumber(51)+300;
 
        if(ScoreCounter == 1
        
            getWorld().addObject(new Shroom(), x, y); 
        
        if(ScoreCounter == 2
        
            getWorld().addObject(new Shroom(), x, y); 
        }
danpost danpost

2013/10/28

#
Lines 6 through 8 must be put in the correct order or you will inadvertently not shift when you need to. Start with the lowest coordinates and work to the highest.
Baenefin Baenefin

2013/10/28

#
So it should be
1
2
3
4
int x = (Greenfoot.getRandomNumber(getWorld().getWidth()-(352-282)-(896-640)-(1200-1088)));
if (x > 282) x += 70;
if (x > 640) x += 256;
if (x > 1088) x += 112;
And I am guessing it works the same for Y's?
danpost danpost

2013/10/28

#
That should work. To explain; if using your previously posted code, you had an x value of 780, the first step would be skipped and the latter two would be executed, adding 326 ( 112 + 256 ) to 780, making 1106, which is in an invalid range.
Baenefin Baenefin

2013/10/28

#
I see. It actually makes sence to me! Thanks.
You need to login to post a reply.
1
2