本文介绍使用原生JavaScript实现两个绝对定位元素的碰撞检测。当检测到碰撞时,目标元素颜色随机改变并反弹至随机位置。代码包含HTML结构、CSS样式及核心JS逻辑,适合前端初学者参考学习。
原生JS碰撞检测实现示例
本文分享了一段使用JavaScript实现碰撞检测的完整代码示例,供读者参考学习。
这里演示了一个基础的碰撞检测逻辑:判断box1与box2是否发生重叠。若检测到碰撞,box2的颜色将随机改变,并反弹至屏幕内的随机新位置。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box1,.box2{
width: 100px;
height: 100px;
background-color: #f00;
position:absolute;
}
.box2{
background-color: #00f;
left: 200px;
top: 200px;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
<script>
var box1=document.querySelector(".box1");
var box2=document.querySelector(".box2");
box1.addEventListener("mousedown",mouseHandler);
function mouseHandler(e){
if(e.type==="mousedown"){
e.preventDefault();
document.elem=this;
document.pointX= e.offsetX;
document.pointY= e.offsetY;
document.addEventListener("mousemove",mouseHandler);
this.addEventListener("mouseup",mouseHandler);
}else if(e.type==="mousemove"){
this.elem.style.left= e.x-this.pointX+"px";
this.elem.style.top= e.y-this.pointY+"px";
hitText(this.elem,box2);
}else if(e.type==="mouseup"){
document.removeEventListener("mousemove",mouseHandler);
this.removeEventListener("mouseup",mouseHandler);
}
}
function hitText(elem1,elem2){
var rect1=elem1.getBoundingClientRect();
var rect2=elem2.getBoundingClientRect();
var ponit1={x:rect1.x,y:rect1.y};
var ponit4={x:rect1.x+rect1.width,y:rect1.y+rect1.height};
if(
ponit4.x>rect2.x
&&ponit1.x<(rect2.x+rect2.width)
&&ponit4.y>rect2.y
&&ponit1.y<(rect2.y+rect2.height)){
elem2.style.backgroundColor=randomColor();
elem2.style.left=Math.round(Math.random()*document.documentElement.clientWidth)+"px";
elem2.style.top=Math.round(Math.random()*document.documentElement.clientHeight)+"px";
}
}
function randomColor(){
var a=Math.round(Math.random()*255);
var b=Math.round(Math.random()*255);
var c=Math.round(Math.random()*255);
var color="rgb("+ a+","+b+","+c+")";
return color;
}
</script>
</html>
以上就是该碰撞检测示例的全部内容,希望对学习JavaScript前端开发的朋友有所帮助,欢迎继续支持本站获取更多技术分享。