【发布时间】:2022-01-09 21:34:09
【问题描述】:
我用 vanilla js 为网络创建了一个游戏。我希望控制台检测两个 <img> 标签之间的冲突。我正在使用 DOM 来检索项目。使用箭头,我可以移动其中一张图像。
问题:当他们互相接触时,控制台没有检测到任何东西。上面写着:没有碰撞。我需要碰撞才能进入下一页/场景。
console.log('collisions');
// collision entre la limite et le personnage
let rect1 = document.getElementsByClassName('perso')
let rect2 = document.getElementsByClassName('obstacle');
console.log(rect1[0]);
console.log(rect2[0]);
if (rect1[0].x < rect2[0].x + rect2[0].width &&
rect1[0].x + rect1[0].width > rect2[0].x &&
rect1[0].y < rect2[0].y + rect2[0].height &&
rect1[0].height + rect1[0].y > rect2[0].y) {
console.log("collision");
// window.location.href = 'htmlpage1.html';//passe à la page/scene suivante
} else {
console.log("no collision");
}
#move {
height: 300px;
width: 300px;
position: relative;
z-index: 1;
}
/* limite de la page permet de passer à la scene suivante */
#limite {
width: 150px;
height: 250px;
position: fixed;
z-index: 2;
margin: 30px 1100px;
opacity: 50%;
}
<main>
<div class="cadre">
<img id="premierplan" src="../img/foreground.png" alt="premierplan">
<img id="move" class="perso" src="../img/ne_bouge_pas_.gif" alt="image personnage">
<img id="limite" class="obstacle" src="../img/carrebleu.png" class="cube" alt="frontiere">
</div>
</main>
【问题讨论】:
标签: javascript html collision detection