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

2013/3/10

How do i remove a object?

kante162 kante162

2013/3/10

#
I am programming a little pause screen for my 2D jump'n'run -game.
    public boolean pause()
    {
        gameWorld1 theWorld = (gameWorld1) getWorld();
        PauseScreen pauseScreen = new PauseScreen();
        if(Greenfoot.isKeyDown("escape"))
        {
            theWorld.addObject(pauseScreen, 500, 300);
            Greenfoot.delay(10);

            answer = true;
        }
        else if(Greenfoot.isKeyDown("enter"))
        {
            theWorld.removeObject(pauseScreen);
            Greenfoot.delay(10);
            answer = false;
        }
        return answer;
    }
It simply does create a object named pauseScreen, if the escape-button is pressed and all actors extending the Pause-class stop executing the act()-method. It works quite fine, it also does resume to the game, if the enter-button is pressed, but it doesn't remove the pauseScreen-object, although i have used the removeObject()-method. I have no clue why this doesn't work. Could anybody help me please?
Gevater_Tod4711 Gevater_Tod4711

2013/3/10

#
The problem is that you create a new pauseScreen every time the method is executet. And then if you press the enter button the world tries to remove a new object which isn't even in the world. Try using this instead:
//...
else if(Greenfoot.isKeyDown("enter"))  {  
    theWorld.removeObject(theWorld.getObjects(PauseScreen.class));  
    Greenfoot.delay(10);  
    answer = false;  
}  
return answer;  
This will remove every pauseScreen that is in the world at the moment.
kante162 kante162

2013/3/10

#
Thank you really much :)
danpost danpost

2013/3/10

#
The 'removeObject' method is being used (at line 14) to remove the 'pauseScreen' object that is created at line 4. This PauseScreen object has not yet been placed in the world so nothing is actually removed. The remove the one that is already in the world, change line 14 to
theWorld.removeObjects(theWorld.getObjects(PauseScreen.class));
(1) You can remove the 'answer' field totally (remove lines 10, 16 and 18; also, the 'answer' field declaration in this class; and change the method declaration to 'public void pause()' ). Use '!getWorld().getObjects(PauseScreen.class).isEmpty()' as a substitute for 'answer' elsewhere in the class. (2) Move line 4 to just before line 7. That object does not need created unless 'escape' is pressed. (3) Try adding a timer to create the delay instead of using the 'delay' method. However, I believe that this would be one of the few cases where using the 'delay' method would be ok.
You need to login to post a reply.