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

2012/11/22

Adding An Object to a World

jmextratall jmextratall

2012/11/22

#
How can I use a conditional statement in my addObject loop to ensure that the object I add is not cut off by the edge of the world? In other words, I need to apply a condition such that the new object added is entirely within the world. I have to add five objects at random locations that meet that criteria. I can add five objects at random locations, but I can't yet guarantee that all five are completely within the world and not at all cut off by the edge. Any help would be appreciated!
danpost danpost

2012/11/22

#
First add it to the world, then check its coordinates with those of the edges of the world plus or minus half its image's dimensions; adjusting accordingly. You could use a 'do' loop to randomly set the location of the object until it is within boundary limits of all four edges; or you could have four individually check (one for each edge) and if outside the edge's limit, move the object back to the limit of that edge.
jmextratall jmextratall

2012/11/22

#
But how can I do that as variable, to account for an image of any size?? Here is how I have attempted it so far, which works, except I can't guarantee 5 objects every time.
for(int i = 0; i < 5; i++)
        {
            int x = Greenfoot.getRandomNumber(getWidth() - 50);
            int y = Greenfoot.getRandomNumber(getHeight() - 50);
            if(x >= 50 && y >= 50)
            {
                addObject (new Orb (Greenfoot.getRandomNumber(15), Greenfoot.getRandomNumber(15)),
                x, y);
            }
        }
The
x >= 50 && y >= 50
portion in the conditional statement is meant to accomplish that, but when the random numbers don't meet that condition I don't get an object at all.
danpost danpost

2012/11/22

#
You can change lines 3 and 4 to the following and remove lines 5, 6, and 9.
int x = Greenfoot.getRandomNumber(getWidth() - 100) + 50;
int y = Greenfoot.getRandomNumber(getHeight() - 100) + 50;
The two lines above will, by themselves, restrict the value to the following x >= 50 && x < getWidth() - 50 y >= 50 && y < getHeight() - 50 If your world was 600x400 then x would be 50 to 549 and y would be 50 to 349. So. with that, all that needs done is placing the object at that location.
jmextratall jmextratall

2012/11/22

#
Aha! My father-in-law actually said that but didn't know how to code it. Thank you for filling in the missing gaps for me! I appreciate your help.
You need to login to post a reply.