gpt4 book ai didi

JavaScript:碰撞检测不起作用

转载 作者:行者123 更新时间:2023-12-02 15:15:29 25 4
gpt4 key购买 nike

我正在用 JavaScript 制作一个游戏,其中有一颗子弹朝你飞来,你需要跳过它。

这是我的代码:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Over The Top Game</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
#bullet {
-webkit-animation-name: move; /* Chrome, Safari, Opera */
-webkit-animation-duration: 3s; /* Chrome, Safari, Opera */
animation-name: move;
animation-duration: 3s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes move {
from {right: 0px;}
to {right: 100%;}
}

/* Standard syntax */
@keyframes move {
from {right: 0px;}
to {right: 100%;}
}
</style>
</head>
<body style="margin: 0px;">
<img id="bullet" src="bullet.png" style="position:absolute; bottom: 100px; right: 0px;" />
<img id="man" src="stickman.png" style="position:absolute; bottom:50px; left: 100px;" />
<div style="background-color: #654321; width: 100%; height: 50px; position:absolute; bottom:0px;"></div>
<script>
var image = document.getElementById("man");
document.body.onkeydown = function(e){
if(e.keyCode == 32){
var x = 0;
var interval = setInterval(function() {
x++;
image.style.bottom = 50+(-0.1 * x * (x - 75)) + 'px';
if(x >= 75) clearInterval(interval);
}, 20);
}
}
//not working
function collide () {
var box1 = document.getElementById("man");
var box2 = document.getElementById("bullet");
var rect1 = box1.getBoundingClientRect();
var rect2 = box2.getBoundingClientRect();
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.height + rect1.y > rect2.y) {
alert("You lose. Click OK to restart");
location.reload;
}
}
setInterval(collide(), 500);
</script>
</body>
</html>

除了碰撞检测之外,我已经完成了所有工作。如果有人能看到我出错的地方并纠正它,那将是一个很大的帮助。

最佳答案

几个问题:

setInterval(collide(), 500);

这会调用collide,并尝试使用其返回值作为setInterval的参数。

你想要这个:

setInterval(collide, 500);

这实际上告诉 setInterval 调用 collide

另一个问题是 getBoundingClientRect 返回的矩形没有 xy 属性,但有 top >、rightbottomleft,因此您必须使用此条件:

if (rect1.left < rect2.right &&
rect1.right > rect2.left &&
rect1.top < rect2.bottom &&
rect1.bottom > rect2.top) {

关于JavaScript:碰撞检测不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34511739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com