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

2019/11/18

Next Level

HEISENBERG HEISENBERG

2019/11/18

#
So in my game, after I get 5 coins, I want a door to appear. When the user interacts with the door, he goes to the next level. For some reason, once I collect 5 coins on level 1 and hit the door, it puts me straight onto level 3. Here is a bit of code that does the coin collecting:
private int coinsCollected = 0;
    private boolean fiveCoinsLevel1 = false;
    private boolean fiveCoinsLevel2 = false;
    private boolean fiveCoinsLevel3 = false;
private void collect () {
        Actor coin = getOneIntersectingObject(Coin.class);

        if (coin != null) {
            getWorld().removeObject(coin);
            coinsCollected++;
        }
if (coinsCollected == 5 && fiveCoinsLevel1 == false) {
        	if (this.getWorld().getClass() == Level_1.class) {
        		getWorld().addObject(new door_temp(), 157, 162);
        		fiveCoinsLevel1 = true;
        		secondLevel();
        		coinsCollected = 0;
        	}
        }

        if (coinsCollected == 5 && fiveCoinsLevel2 == false && fiveCoinsLevel1 == true) {
        	if (this.getWorld().getClass() == Level_2.class) {
        		getWorld().addObject(new door_temp(), 157, 162);
        		fiveCoinsLevel2 = true;
        		thirdLevel();
        	}
        }
    }
HEISENBERG HEISENBERG

2019/11/18

#
Forgot to include these!
public void secondLevel ()  {
    	Actor secondlvl = getOneIntersectingObject(door_temp.class);

    	if (secondlvl != null) {
    		Greenfoot.setWorld(new Level_2());
    	}
    }

    public void thirdLevel ()  {
    	Actor thirdlvl = getOneIntersectingObject(door_temp.class);

    	if (thirdlvl != null) {
    		Greenfoot.setWorld(new Level_3());
    	}
    }
danpost danpost

2019/11/18

#
First, there is no need for any of the boolean fields. In fact, as soon as you change levels, they all become false again, anyway. Second, you can add the door at the moment the coin counter reaches 5:
if (isTouching(Coin.class))
{
    removeTouching(Coin.class);
    coinsCollected++;
    if (coinsCollected == 5) getWorld().addObject(new door_temp(), 157, 162);
}
Lastly, you can check the level when changing worlds:
public void nextLevel()
{
    if (isTouching(door_temp.class))
    {
        World go2world = null;
        if (getWorld() instanceof Level_1) go2world = new Level_2();
        else if (getWorld() instanceof Level_2) go2world = new Level_3);
        // else if ...
        if (go2world != null) Greenfoot.setWorld(go2world);
        // else end game
    }
}
You need to login to post a reply.