Skip to content
Advertisement

Check collision, and the do something in js

I have a 2d, top-down game, where there are 2 players; one is controlled by the arrow keys, and the other one is controlled by the WASD keys. I want to make it to where when the 2 players overlap, I can make it to where it stops the program, or I can print something in the console, something like that, anything, really.(TO VIEW THE CODE SNIPPET, YOU HAVE TO CLICK “VIEW FULL PAGE”, TO VIEW THE ENTIRE PROGRAM.)

Here is my code for the whole game in HTML, CSS, and JS:

JavaScript
JavaScript
JavaScript

Advertisement

Answer

Here, I hope this helps! Basically, I call a handler method every time a player moves, checking if the coordinates of the 2 players match. If they do, update an info text stating so. I’ve also cleaned up the key handling code.

The collision detection is rather basic at the moment, please open another question if you’d need more advanced detection (e.g. detect if pieces are only partially colliding etc.)

JavaScript
JavaScript
JavaScript
Advertisement