Implement Scoring and Collision Detection Algorithm
Implement the logic to check if two objects collide and display the score of the player on the canvas.
Introduction
We've now added the player character and the gem objects on the canvas. We have also added the event listeners that we use to move the player character object horizontally. Now, we will add a critical piece of the logic of our game, collision detection, which will detect when the player character (PC) collides with either an enemy (which is a game-over situation, depending upon the health of the player) or collides with a gem (which is a game-winning situation). In terms of coordinates and rectangle objects (since we are drawing rectangle images of the PC, gem, and enemies), a collision occurs between two objects when the x and y coordinate of the first object becomes less than the x + length and y + breadth of the second object, respectively, and the x and y coordinate of the second object becomes less than the x + length and y + breadth of the first object, respectively.
Understanding the collision detection algorithm
The statement that we discussed above regarding the collision between two rectangle objects might be confusing to understand, so we have given the following formula to describe the above statement:
X-Coordinate of first object < (X-Coordinate of second object + Width (length) of the second object) and
Y-Coordinate of first object < (Y-Coordinate of second object + Height (breadth) of the second object) and
X-Coordinate of second object < (X-Coordinate of first object + Width (length) of the first object) and
Y-Coordinate of second object < (Y-Coordinate of first object + Height (breadth) of the first object).
The above formula may look complicated, but the illustration below will help us visualize what it means:
Get hands-on with 1200+ tech skills courses.