欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

原生js实现碰撞检测

时间:2021-02-12 08:48:59|栏目:JavaScript代码|点击:

本文实例为大家分享了js实现碰撞检测的具体代码,供大家参考,具体内容如下

随手写了个简单的碰撞检测的代码。检测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>

上一篇:集合Bootstrap自定义confirm提示效果

栏    目:JavaScript代码

下一篇:Struts2和Ajax数据交互示例详解

本文标题:原生js实现碰撞检测

本文地址:http://www.codeinn.net/misctech/61496.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有