Во время написания мини-игры в JS возникла проблема перепрыгивания персонажа через препятствие
когда left-положение препятствия становится равно ширине персонажа срабатывает alert(Game over). Не понимаю где ошибка в коде, по идее препятствие должно проходить дальше при перепрыгивании персонажем
const dog = document.getElementById('dog');
const fire = document.getElementById('fire');
document.addEventListener('keydown', function(event) {
jump();
});
function jump() {
if (dog.classList !='jump') {
dog.classList.add('jump');
} setTimeout( function() {
dog.classList.remove('jump')
}, 300)
}
let isAlive = setInterval (function() {
let dogTop = parseInt(window.getComputedStyle(dog).getPropertyValue('top'));
let dogLeft = parseInt(window.getComputedStyle(dog).getPropertyValue('width'));
let fireLeft = parseInt(window.getComputedStyle(fire).getPropertyValue('left'));
if (fireLeft<100 && fireLeft>0 && dogTop>=390) {
alert('GAME OVER')
}
}, 10)
.game {
width: 900px;
height: 500px;
border-bottom: 1px solid #000;
margin: auto;
}
#dog {
width: 100px;
height: 100px;
background-image: url(img/dogg.jpg);
background-size: 100px 100px;
position: relative;
top: 400px;
}
#fire {
width: 50px;
height: 80px;
background-image: url(img/fire.png);
background-size: 50px 80px;
position: relative;
top: 310px;
left: 850px;
animation: fireMove 3s infinite linear;
}
@keyframes fireMove {
0% {
left: 850px;
}
100% {
left: -50px;
}
}
.jump {
animation: jump 0.5s linear;
}
@keyframes jump {
0% {
top: 400px;
}
30% {
top: 300px;
}
50% {
top: 300px;
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="game">
<div id="dog"></div>
<div id="fire"></div>
</div>
<script src="script.js"></script>
</body>
</html>
}
80% {
top: 300px;
}
100% {
top: 400px;
}
}
Ответы (1 шт):
Автор решения: the_Solomon
→ Ссылка
Даже не знаю с чего начать
- Убери background-image и поставь вместо dog и fire какой нибудь цвет, и ты увидишь, что коллизия всё же возникает (они дотрагиваются друг к другу).
- Это абсолютно неправильный подход, получать данные о коллизии и позиции элементов игры из CSS, это все должно делаться с помощью JS.
- Вот как правильно проверять коллизию: https://www.youtube.com/watch?v=_MyPLZSGS3s&t=113s&ab_channel=ChrisCourses