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

2017/4/7

Preventing objects from being placed on top of each other

SeaShore SeaShore

2017/4/7

#
In the quiz I'm making, I have a method in the world to generate boxes with the different answers on them. The problem I'm having is that with the method I'm using, sometimes the boxes end up on top of each other so one will be hidden under the other. Here's what that code looks like:
private void createAnswerBank()
    {
       int x = 7*getWidth()/8;
       int y = 14*getHeight()/125;
       int z = 7*getHeight()/125;
        
       for (int i = 0; i<16; i++)
       {
           Button button = new Button(getHeight()/10 +(z*i), score, numberCorrect);
           a = Greenfoot.getRandomNumber(16);
           b = y+(z*a);
           
           addObject(button, x, b);
           
           String image = new String(polyatomicFormulas[i]);
           button.setImage(image);
       }
       
    }
I tried to fix this by adding this method to the Button class, but the method made the buttons constantly move instead of only move when another button was already there.
public void fixPlacement()
    {
        World world = getWorld();
        int y = 14*world.getHeight()/125;
        int z = 7*world.getHeight()/125; 
        
        if (isTouching(Button.class))
        {
           setLocation(7*world.getWidth()/8, y+(z*Greenfoot.getRandomNumber(16))); 
        }
    }
Do you guys have any recommendations on how to fix my fixPlacement method? Or should I try something else entirely to prevent the buttons from overlapping each other?
danpost danpost

2017/4/8

#
SeaShore wrote...
Do you guys have any recommendations on how to fix my fixPlacement method? Or should I try something else entirely to prevent the buttons from overlapping each other?
Well, you should not try to adjust their positions from the Button class (remove thee 'fixPlacement' method from the class). It appears to me that you have 16 possible answers and you are trying to shuffle them while placing then into the world. I would prefer to shuffle the buttons first, then add them into the world in their shuffled ordering. It is, however, possible to shuffle them while adding them into the world -- it just takes a little more coding. Basically, you need to reject placing an button at a location where a button already exists. At line 12 in the 'createAnswerBank' method, add the following line:
while (!getObjectsAt(x, b, Buttton.class).isEmpty()) b = y+z*Greenfoot.getRandomNumber(16);
You need to login to post a reply.