您的位置:首页 > 其它

碰撞检测

2016-07-13 19:22 281 查看
<!DOCTYPE html>
<html>

<head>
<meta
charset="UTF-8">
<title></title>
<style
type="text/css">
.wrap
{
width:
600px;
height:
400px;
border:
1px solid black;
position:
relative;
}

.snake
{
width:
50px;
height:
50px;
background-color: aquamarine;
position:
absolute;
}

.food
{
width:
50px;
height:
50px;
background-color: pink;
position:
absolute;
left:
200px;
top:
200px;
}
</style>
</head>

<body>
<div
class="wrap">
<div
class="snake"></div>
<div
class="food"></div>
</div>
<script
type="text/javascript">
var
wrap = document.querySelector(".wrap");
var
snake = document.querySelector(".snake");
var
food = document.querySelector(".food");
snake.onmousedown
= function() {
var
l = snake.offsetLeft;
var
t = snake.offsetTop;
var
x = event.clientX;
var
y = event.clientY;
// 移动一个小div块
document.onmousemove
= function() {
var
x1 = event.clientX;
var
y1 = event.clientY;
var
chaX = x1 - x;
var
chaY = y1 - y;
// 原来的位置上面加上鼠标移动了多少就动多少,,实现小div移动
snake.style.left
= l + chaX +
"px";
snake.style.top
= t + chaY +
"px";
// 碰撞检测
var
sL = snake.offsetLeft;
var
sT = snake.offsetTop;
var
sW = snake.offsetWidth;
var
sH = snake.offsetHeight;
var
fL = food.offsetLeft;
var
fT = food.offsetTop;
var
fH = food.offsetHeight;
var
fW = food.offsetWidth;
// 上下左右四个方向都判断
var
leftBol = sL + sW
>= fL;
var
rightBol = sL <= fL
+ fW;
var
topBol = sT + sH
>= fT;
var
bottomBol = sT <= fT
+ fH;

if
(leftBol && rightBol &&
topBol && bottomBol) {
food.style.backgroundColor
= "chartreuse";
}else{
food.style.backgroundColor
= "";
}

// if ((snake.offsetLeft - food.offsetWidth <= food.offsetLeft ) && (snake.offsetLeft+ snake.offsetWidth >= food.offsetLeft) && (snake.offsetTop - food.offsetHeight <= food.offsetTop)
&& (snake.offsetTop + snake.offsetHeight >= food.offsetTop)) {
// food.style.backgroundColor = "chartreuse";
// }else{
// food.style.backgroundColor = "";
// }

}
document.onmouseup
= function() {
document.onmousemove
= null;
}

}
</script>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  碰撞检测