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

2015/12/21

prevent constructor from resetting values

davemib123 davemib123

2015/12/21

#
Hi All, slightly stuck. How do I prevent the constructor from resetting the constructor values when my hero dies. This is what I have in the constructor:
scoreCounter = new Counter ("Score:");
        lifeCounter = new Counter ("x");
        coinCounter = new Counter ("x");
        lifeCounter.setValue(3);
        scoreCounter.setValue(0);
        coinCounter.setValue(0);
When my hero dies it has this:
 if(getY() >= getWorld().getHeight() + 150){
                getWorld().removeObject(this);
                Greenfoot.delay(50);
                Greenfoot.setWorld(new Level());
            }
That basically resets the world to the first map. How I get it so that the constructor sticks to its values i.e. 3 lives, 2 lives, 1 life. Thanks in advance!
danpost danpost

2015/12/21

#
One way is to set up a reference to the new Level1 world and replace the new counter with the old one:
// starting line 4 in hero
Level1 newWorld = new Level1();
Actor counter = ((Level1.getWorld()).lifeCounter;
Actor badCounter = newWorld.lifeCounter;
newWorld.addObject(counter, badCounter.getX(), badCounter.getY());
newWorld.removeObject(badCounter);
newWorld.lifeCounter = counter;
Greenfoot.setWorld(newWorld);
davemib123 davemib123

2015/12/25

#
thanks danpost that works :)
You need to login to post a reply.