I’m building a simple Pac-Man game using JavaScript. The game features Pac-Man navigating a maze, collecting points (dots), and avoiding ghosts. Pac-Man moves using arrow keys, and the game updates the score when dots are collected.
I’m having trouble implementing collision detection for:
- Detecting when Pac-Man touches a ghost (game over).
- Detecting when Pac-Man collects a dot (score update and dot disappears).
What I have attempted
- For dot collision detection:
I attempted to check if Pac-Man’s position matches the dot’s position using getBoundingClientRect():
const pacmanRect = pacman.getBoundingClientRect();
const dotRect = document.getElementById('dot1').getBoundingClientRect();
if (
pacmanRect.left < dotRect.right &&
pacmanRect.right > dotRect.left &&
pacmanRect.top < dotRect.bottom &&
pacmanRect.bottom > dotRect.top
) {
console.log('Dot collected!');
}
However, this only works sometimes and isn’t consistent when Pac-Man moves quickly.
- For ghost collision detection:
I tried a similar approach, but the game doesn’t detect collisions reliably.
Additional Attempts:
Using setInterval
to check for collisions at regular intervals.
Reducing the size of the bounding boxes for better accuracy.
Expected Behavior
- When Pac-Man collides with a dot, the dot should disappear, and the score should update.
- When Pac-Man collides with a ghost, the game should display a "Game Over" message.
2
Answers
For your code to work, pacman would have to be smaller than the dot
and then be lined up exactly over it.
If you change the test logic to ensure that pacman is outside of the dot’s rectangle,
then negate the comparison, then any amount of overlap between the two objects
will be considered a collision.
If all of Pacman is to the right of the dot then there can be no overlap.
This can be tested by: pacmanRect.left > dotRect.right
Similarly if all of Pacman is to the left of the dot, or above the dot, or below the dot there can be no overlap.
You therefore want to test for whether it’s to the right OR to the left OR above OR below.
And if it is then there is no overlap.