Yesterday I announced that a new Greenfoot version is available (version 2.1). Over the next few days, I’ll go through some of the new features and introduce them briefly here. This is the first one: the setWorld(…) method.
The Greenfoot class now has a method with the following signature:
setWorld (World world)
This method takes a world object as a parameter, and it will show that world in the Greenfoot main window.
This allows you to have multiple World subclasses (in my example called Level1 and Level2). You can then dynamically (that is: while your program is running) create and install other world objects. These other worlds can show entirely different scenes, such as other levels.
For example, to go to Level 2, you could use the following statement:
Greenfoot.setWorld(new Level2());
Of course, the same initialisation applies as usual: If the Level2 world creates and inserts some actors in it’s constructor, this will all happen.
One thing to keep in mind, though, is that this will – if you don’t do anything clever – create new actors. So, if you have a game character in level 1, an then you add a game character to level 2, you will have a new character object. If you stored some state (e.g. a score) in the instance variables of that actor, it will be gone. If you want to preserve the state of your game character, make sure you carry the actor object across without creating a new one.
An example showing this new functionality in action is now on the Greenfoot Gallery, here.