簡單前端——圓與圓碰撞檢測

Roninwz發表於2017-09-25

只是沒什麼做搞個來玩玩,順便練練手

滑鼠按著紅球,就可以移動紅球,如果以黃球發生碰撞,紅球就變為綠球,否則顏色不變。



[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title></title>  
  6.     <style>  
  7.         #a , #b {  
  8.             width: 100px;  
  9.             height: 100px;  
  10.             position: absolute;  
  11.             border-radius: 50%;  
  12.         }  
  13.         #a{  
  14.             left: 0;  
  15.             top: 0;  
  16.             background-color: red;  
  17.             z-index: 1;  
  18.         }  
  19.         #b {  
  20.             left: 0;  
  21.             top: 0;  
  22.             right: 0;  
  23.             bottom: 0;  
  24.             margin: auto;  
  25.             background-color: yellow;  
  26.         }  
  27.     </style>  
  28. </head>  
  29. <body>  
  30.     <div id="a"></div>  
  31.     <div id="b"></div>  
  32. <script>  
  33.     var a = document.getElementById('a');    
  34.     var b = document.getElementById('b');  
  35.     a.onmousedown = function (ev) {   
  36.         aX = ev.clientX - a.offsetLeft;    
  37.         aY = ev.clientY - a.offsetTop;  
  38.         document.onmousemove = function (ev) {  
  39.             var t1 = a.offsetTop;    
  40.             var l1 = a.offsetLeft;  
  41.   
  42.             var t2 = b.offsetTop;    
  43.             var l2 = b.offsetLeft;   
  44.             if (Math.sqrt(Math.pow(t1 - t2, 2) + Math.pow(l1 - l2, 2)) <= 100) {    
  45.                 // 如果兩圓的圓心距小於或等於兩圓半徑和則認為發生碰撞    
  46.                 a.style.background = 'green';  
  47.             }else{  
  48.                 a.style.background = 'red';  
  49.             }  
  50.   
  51.             a.style.left = ev.clientX - aX +'px';    
  52.             a.style.top = ev.clientY - aY +'px';    
  53.         }  
  54.         document.onmouseup = function () {    
  55.             document.onmousemove = null;    
  56.             document.onmouseup = null;    
  57.   
  58.         }    
  59.         return false;    
  60.     }  
  61. </script>  
  62. </body>  
  63. </html>  


轉載來自:http://blog.csdn.net/zhuxiongyin/article/details/71499843

相關文章