简体   繁体   中英

JavaScript: Collision Detection Not Working

I am making a game with JavaScript where there is a bullet coming towards you and you need to jump over it.

Here is my code:

<!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>

I have got everything working except the collision detection. If anyone can see where I am going wrong and correct it that would be a great help.

Several issues:

setInterval(collide(), 500);

This calls collide , and tries to use its return value as the argument to setInterval .

You want this instead:

setInterval(collide, 500);

This actually tells setInterval to call collide .

The other issue is that the rectangle returned by getBoundingClientRect does not have x or y properties, but top , right , bottom and left , so you'll have to use this condition:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM