首先我们先要了解一下碰撞检测有什么用?
碰撞检测常用于游戏开发,通过碰撞检测判断前面是否有障碍物以及两个物体是否发生碰撞,根据检测的结果做出不同的处理,
碰撞检测就是查看物体是否重合
下面写一个简单的碰撞检测代码
首先创建两个正方形div
<div id="box1">移动</div>
<div id="box2">障碍</div>
在设置颜色
div{
width:100px;
height: 100px;
position: absolute;
background: bisque;
text-align: center;
line-height: 100px;
color:rebeccapurple;
}
#box2{
left:300px;
top:200px;
}
写出移动正方形判断是否碰撞
var box = document.getElementsByTagName('div');
box[0].onmousedown = function(){
var disX = event.clientX - this.offsetLeft;
var disY = event.clientY - this.offsetTop;
document.onmousemove = function(){
box[0].style.left = event.clientX - disX + "px";
box[0].style.top = event.clientY - disY + "px";
if(collision(box[0],box[1])){
//碰到了
box[1].style.background = "pink"
}else{
box[1].style.background = "lightseagreen";
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
这边把检测写成函数了
function collision(obj1,obj2){
//obj1的四条边
var l1 = obj1.offsetLeft;
var r1 = l1 + obj1.offsetWidth;
var t1 = obj1.offsetTop;
var b1 = t1 + obj1.offsetHeight;
//obj2的四条边
var l2 = obj2.offsetLeft;
var r2 = l2 + obj2.offsetWidth;
var t2 = obj2.offsetTop;
var b2 = t2 + obj2.offsetHeight;
if(r2 < l1 || b2 < t1 || l2 > r1 || t2 > b1){
return false
}else{
return true
}
}
调用函数, obj是要指定传参数
function drag(obj){
obj.onmousedown = function(){
//记录鼠标在元素上的坐标位置
var disX = event.clientX - this.offsetLeft;
var disY = event.clientY - this.offsetTop;
document.onmousemove = function(){
obj.style.left = event.clientX - disX + "px";
obj.style.top = event.clientY - disY + "px";
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
}
drag(box[1])