041 : Collide with goal

Balthazar:

We show the goal on the screen, but we want to detect when the player touches the goal and then end the game.

Balthazar:

The first thing we need is a boolean variable that keeps track of whether or not the game is over. This should be initialized to false.

script.js: Add game_over variable.
function init_game() { ... // Game state. _game.game_over = false; _game.platform = create_platform(0, 360, _game.width, 40); _game.goal = create_goal(500, 360); // Global world parameters. ... }
Balthazar:

Now that we have this variable, we can set it to true when the player touches (collides with) the goal that we just added.

Balthazar:

We can add a check_goal_collisions() function to detect when the player collides with the goal object. If that happens, we set the game_over flag to true.

Balthazar:

We're also temporarily adding a "dummy" version of the collide() function. This dummy version does nothing except return false (meaning no collision found). We'll be creating a proper version of collide() once we finish hooking up the goal collision code. We'll add a "NYI" comment to indicate that it's "Not Yet Implemented".

script.js: Create the check_goal_collisions() function.
function check_input() { ... } function check_goal_collisions() { var goal = _game.goal; if (collide(goal, _player)) { _game.game_over = true; } } // Return true if the 2 objects overlap. function collide(obj1, obj2) { // NYI return false; } // This is called ~60 times per second to update the world. function update_world() { ... }
Balthazar:

Since we'll be doing a lot more collision detection, we might as well create a check_collisions() function that will check for all the collisions that we care about in the game.

Balthazar:

Right now, we only have goal collisions, so we only need to call check_goal_collisions(). We'll be adding more to this function later.

function check_input() { ... } function check_collisions() { check_goal_collisions(); } function check_goal_collisions() { ... }
Balthazar:

And finally, we need to call our check_collisions() function. We need to do that in update_world() so that the game checks for collisions whenever anything moves on the screen.

// This is called ~60 times per second to update the world. function update_world() { update_player(); check_collisions(); draw(); requestAnimationFrame(update_world); }
Balthazar:

The only thing missing is a proper collide() function. We'll add that now.

GOTO 045