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

2011/12/29

Code not working?

kiarocks kiarocks

2011/12/29

#
Why does this code add the object, but not remove it?
if("i".equals(Greenfoot.getKey()) && !pressed)
        {
            getWorld().addObject(instr,350,250);
            pressed = true;
            System.out.println(Boolean.toString(pressed));
        }
        else if("i".equals(Greenfoot.getKey()) && pressed)
        {
            getWorld().removeObject((Instruct)getWorld().getObjects(Instruct.class).get(0));
            System.out.println("Removed");
            pressed = false;
        }
Note: this prints out true in the window, and if you remove the ' "i".equals(Greenfoot.getKey()) ' from the else if and make it just pressed, it prints out "true removed".
DonaldDuck DonaldDuck

2011/12/29

#
Change line 9 to:
getWorld().removeObjects(getWorld().getObjects(Instruct.class));
This way it will remove all the Instruct objects in the world. I'm assuming instruct is just a text area for instructions, so you should only ever have 1 in the world anyways. You don't need to remove only 1.
DonaldDuck DonaldDuck

2011/12/29

#
I think I misunderstood you. Maybe try this in place of yours.
if("i".equals(Greenfoot.getKey()))
{
    if(!pressed)  
    {  
        getWorld().addObject(instr,350,250);  
        pressed = true;  
       System.out.println(Boolean.toString(pressed)); 
        return; 
    }  
    else if(pressed)  
    {  
        getWorld().removeObject((Instruct)getWorld().getObjects(Instruct.class).get(0)); 
        System.out.println("Removed");  
        pressed = false;
        return;
    }  
}
kiarocks kiarocks

2011/12/29

#
yay it works!
danpost danpost

2011/12/29

#
kiarocks -- just wanted to explain the main problem with the original code you posted. It was in line 7, where you called 'Greenfoot.getKey()' a SECOND time. This will always return null AFTER the first call. That is why line 7 always returned false and never executed the code that would perform when a true value is returned. Another solution is to start your code with
String key = Greenfoot.getKey();
and replace your 'Greenfoot.getKey()'s with 'key'.
kiarocks kiarocks

2011/12/29

#
ok, i thought that might be the case.
You need to login to post a reply.