-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
41 lines (34 loc) · 1.09 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const player = document.getElementById('player');
const obstacle = document.getElementById('obstacle');
let isGameOver = false;
document.addEventListener('keydown', (event) => {
if (!isGameOver) {
if (event.key === 'ArrowLeft' && player.style.left !== '0px') {
movePlayer(-50);
} else if (event.key === 'ArrowRight' && player.style.left !== '350px') {
movePlayer(50);
}
}
});
function movePlayer(distance) {
const currentPosition = parseInt(player.style.left) || 0;
const newPosition = currentPosition + distance;
player.style.left = newPosition + 'px';
}
function checkCollision() {
const playerRect = player.getBoundingClientRect();
const obstacleRect = obstacle.getBoundingClientRect();
if (
playerRect.top < obstacleRect.bottom &&
playerRect.bottom > obstacleRect.top &&
playerRect.left < obstacleRect.right &&
playerRect.right > obstacleRect.left
) {
gameOver();
}
}
function gameOver() {
isGameOver = true;
alert('Game Over! You collided with the obstacle.');
}
setInterval(checkCollision, 10);