093 : Connecting the levels

Balthazar:

To connect the levels, we need to modify the goal so that it indicates the next level to go to.

Balthazar:

Since we don't have a "game over" level, we'll (temporarily) connect the last level back to the first.

You:

doesn't that mean that the game will never yet.

Balthazar:

Yes, but it's only temporary. We'll be adding a proper ending later.

function create_goal(x, y) { function create_goal(x, y, next_level) { var goal = {}; goal.x = x; goal.y = y; goal.width = 20; goal.height = 20; goal.origin_x = goal.width / 2; goal.origin_y = goal.height; goal.next_level = next_level; return goal; }
Balthazar:

and update all the calls:

function init_level1() { ... add_monsters(level, monster_data); level.goal = create_goal(500, 360); level.goal = create_goal(500, 360, 1); ... } function init_level2() { ... add_default_platforms(level); level.goal = create_goal(500, 360); level.goal = create_goal(500, 360, 2); ... } function init_level3() { ... add_default_platforms(level); level.goal = create_goal(500, 360); level.goal = create_goal(500, 360, 0); ... }
Balthazar:

level1 is at index #0 (_level[0]) and its goal points to level2 (@ index #1)

Balthazar:

Add start_level:

function create_goal(x, y, next_level) { ... } function start_level(level_id) { _game.current_level = level_id; var level = _levels[level_id]; _player.x = level.player_start_x; _player.y = level.player_start_y; _player.velocity_x = 0; _player.velocity_y = 0; } // Erase the canvas and draw all the objects. function draw() { ... }
Balthazar:

When we start a level, we move the player to the appropriate starting location and remove any velocity they may have from the previous level.

function check_goal_collisions() { var level = _levels[_game.current_level]; var goal = level.goal; if (collide(goal, _player)) { _game.game_over = true; _game.game_win = true; start_level(goal.next_level); } }
You:

Wait, now there's no way to win.

Balthazar:

We should also call this after we finish initializing so that the game starts at the correct level.

function handle_load(event) { init(); start_level(0); requestAnimationFrame(update_world); }
You:

don't we already do this in init_game()

Balthazar:

Now that we init the player at the start of each level, we no longer need to set x and y in init_player

function init_player() { // Player x,y are initialized by the level. _player.x = 20; _player.x = 0; _player.y = 360; _player.y = 0; _player.width = 20; _player.height = 20; ... }

Congratulations! You've earned the Transition I - Levels badge!

RUN your code in a browser and verify that it loads without errors.

GOTO 098