JS碰撞检测
视图理解://div1的上边大于div2的下边,,div1的右边小于div2的左边,,div1的上边大于div2的下边,,div1的左边大于div2的右边,这四种情况,问题是没有碰撞/重叠,如下:
<style type=”text/css”>
*{ list-style:none; text-align:center; font-size:14px; color:#fff; font-family:”微软雅黑”}
body{ list-style:none; margin:0; padding:0; border:0;}
html,body{ height:100%}
p,input,li,ul,a,span,button,div,select,p,{ display:inline-block; list-style:none; padding:0; margin:0; text-align:center;outline:none; color:#fff; font-weight:bold; font-size:14px; font-family:”微软雅黑”}
a{width:20px; height:20px; line-height:20px; display:inline-block;}
input{ background:#afa; width:260px; border:0}
input.end{ background:#cf60;}
span{ overflow:hidden; display:block; float:right;margin:0; margin-left:14px;color:#333; cursor:pointer}
div{ margin:0 auto; width:100px;height:100px; overflow:hidden; border:1px solid #fc0; background:rgba(255,102,0,1); margin:60px auto; position:relative}
.div1{ background:rgba(0,204,153,1)}
input{ background:#39C; border-radius:5px;width:160px; height:40px; cursor:pointer; margin:15px}
p{ display:none}
p,ul{ width:100%; height:100%; position:relative; padding:0; margin:0 }
ul li{ width:125px; height:160px; overflow:hidden; float:left;}
</style>
<script type=”text/javascript”>
window.onload=function(){
var zIndex=1;
var div1=document.getElementById(“div1”);
var div2=document.getElementById(“div2”);
div1.onmousedown=function(event){
var this_=this;
var event=event || window.event;
var Dx=event.clientX;
var Dy=event.clientY;
this.style.zIndex=zIndex++;
document.onmousemove=function(event){
var event=event || window.event;
var Mx=event.clientX-Dx;
var My=event.clientY-Dy;
this_.style.left=Mx+”px”;
this_.style.top=My+”px”;
console.log(Mx);
//物体1的上下左右自适应值
var left1=div1.offsetLeft;
var right1=left1 + div1.offsetWidth;
var top1=div1.offsetTop;
var bottom1=top1 + div1.offsetHeight;
//物体2的上下左右自适应值
var left2=div2.offsetLeft;
var right2=left2 + div2.offsetWidth;
var top2=div2.offsetTop;
var bottom2=top2 + div2.offsetHeight;
console.log(top2);
console.log(bottom1);
//div1的上边大于div2的下边,,div1的右边小于div2的左边,,div1的上边大于div2的下边,,div1的左边大于div2的右边,这四种情况,问题是没有碰撞/重叠
if(bottom2<top1 || right1<left2 || bottom1<top2 || right2<left1){// 表示没碰上
// console.log(“两个物体没有碰撞”);
}else{
console.log(“两个物体碰撞”);
}
}
}
document.onmouseup=function(eve){
document.onmousedown=null;
document.onmousemove=null;
}
}
</script>
</head>
<body>
<div id=”div1″></div>
<div class=”div1″ id=”div2″></div>
</body>