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

2019/5/29

Cannot Remove Acto in myWorld when I Click another Actor

AlexandraGrace812 AlexandraGrace812

2019/5/29

#
This is a really boring, kind of stupid game that I have to program for class. Everything else works. I've set up all my actors and the world (lvl3). I want to be able to place "selectors" (they are blue buttons. Class: selector3; Variable name: selector) on various questions. There are four questions and each of them have a different amount of options to choose from. I've worked out the code to create the selectors where I want them when I click an object, but I can't get the selector to delete when I click another option. Here is my code for the first option in one of the questions:
import greenfoot.*;

public class style2 extends style
{
    /**
     * Act - do whatever the style2 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    World myWorld;
    public style2(World world)
    {
       myWorld = world;
       int percentage = 65;
       GreenfootImage image = getImage();
       image.scale(image.getWidth()*percentage/100, image.getHeight()*percentage/100);
    }
    
    public void act() 
    {
       Actor selector = new selector3();
        if (Greenfoot.mouseClicked(this)) {
            
            myWorld.addObject(selector, this.getX(), this.getY());
            
        }
        if (Greenfoot.mouseClicked(style1.class) || Greenfoot.mouseClicked(style3.class)) {
            myWorld.removeObject(selector);
        }
    }    
}
When I select an option, the selector shows up, but if I select another option within the same question (or any other option on the page), a new selector will be created without deleting the first one. How do I make other selectors disappear when other options (within the same question) are clicked?
danpost danpost

2019/5/29

#
Move line 21 to outside of the method. As is, you are creating a different selector3 object every act step; so, if one is added to the world, it will not be referenced when it is time to remove it. A different selector3 object (the one created on that act step) will be referenced.
You need to login to post a reply.