圆形碰撞

一思想

1.利用border-radius: 50%建立两个圆,然后让其中一个可以移动

2.当两个圆圆心距小于等于半径之和时,另一个变色,表示碰撞到

二代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    body{margin: 0}
    #div1{width: 100px;height: 100px;background: red;
      position: absolute;left: 0;top: 0;border-radius: 50%}
    #div2{width: 100px;height: 100px;background: green;
      position: absolute;left: 500px;top: 200px;border-radius: 50%}
  </style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
<script>
  var div1=document.getElementById('div1')
  const div2=document.getElementById('div2')
  div1.onmousedown=function (event) {
    //console.log(div1.offsetLeft)
    var chaX=event.clientX-div1.offsetLeft
    var chaY=event.clientY-div1.offsetTop
    document.onmousemove=function (event) {
      div1.style.left=event.clientX-chaX+'px'
      div1.style.top=event.clientY-chaY+'px'
      
      if(Math.pow((div1.offsetLeft-div2.offsetLeft),2)+
      Math.pow((div1.offsetTop-div2.offsetTop),2)>
          Math.pow((div1.offsetWidth/2+div2.offsetWidth/2),2)){
      div2.style.background=''
      }else{
        div2.style.background='black'
      }
      
    }
    document.onmouseup=function () {
      document.onmousemove=null
    }
  }



</script>

 

posted @ 2021-12-05 11:59  蘑菇萌萌哒  阅读(56)  评论(0)    收藏  举报