1. 程式人生 > >JavaScript碰撞檢測原理及其實現

JavaScript碰撞檢測原理及其實現

1.模擬碰撞

簡單模擬碰撞過程,用一個可以拖拽的div2去嘗試碰撞一個固定的div1(均用絕對定位)

2.碰撞檢測原理

這裡寫圖片描述
如圖所示:
使得div分別有4個距離屬性( L(left),T(top),R(right),B(bottom) ).
對於div1來說,畫出一個九宮格,div2在除中心以為的8個格子任意移動都不會發送碰撞.

這裡寫圖片描述
也就是說,只要滿足條件:oDiv2.div2R小於oDiv1.div1L|| oDiv2.div2L大於oDiv1.div1R || oDiv2.div2B小於oDiv1.div1T|| oDiv2.div2T大於oDiv1.div1B就不會發送碰撞

3.具體測試程式碼

<html>
<head>
    <title></title>
    <style type="text/css">
    body{margin: 0;padding: 0;}
    #div2{height: 100px;width: 200px;background-color: orange;position: absolute;left: 0px;top:0px;z-index: 1;}
    #div1{height: 100px;width: 100px;background-color: #a6e22e;position
: absolute
;left: 600px;top:400px;}
</style> <script type="text/javascript"> //獲取物件樣式屬性值 function getObjStyle(obj,attr) { return getComputedStyle(obj)?getComputedStyle(obj)[attr]:obj.currentStyle[attr]; } </script> <script type="text/javascript"> window.onload=function
(){
var oDiv1=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); oDiv2.onmousedown=function (onEvent,obj){//對div1實現拖拽,並對碰撞進行檢測 obj=this; var ev=onEvent||event; var distance={}; distance.disX=ev.clientX-obj.offsetLeft;//到左邊框的距離 distance.disY=ev.clientY-obj.offsetTop;//到上邊框的距離 //獲取div1的四個值 oDiv1.div1L=getObjStyle(oDiv1,'left'); oDiv1.div1R=parseInt(getObjStyle(oDiv1,'left'))+parseInt(getObjStyle(oDiv1,'width'))+'px'; oDiv1.div1T=getObjStyle(oDiv1,'top'); oDiv1.div1B=parseInt(getObjStyle(oDiv1,'top'))+parseInt(getObjStyle(oDiv1,'height'))+'px'; if(obj.setCapture) obj.setCapture(); document.onmousemove=function (onEvent){ var ev=onEvent||event; obj.style.left=ev.clientX-distance.disX+'px'; obj.style.top=ev.clientY-distance.disY+'px'; //獲取div2的四個值 oDiv2.div2L=getObjStyle(oDiv2,'left'); oDiv2.div2R=parseInt(getObjStyle(oDiv2,'left'))+parseInt(getObjStyle(oDiv2,'width'))+'px'; oDiv2.div2T=getObjStyle(oDiv2,'top'); oDiv2.div2B=parseInt(getObjStyle(oDiv2,'top'))+parseInt(getObjStyle(oDiv2,'height'))+'px'; /*console.log('oDiv2.div2L:'+oDiv2.div2L+' oDiv2.div2R:'+oDiv2.div2R+' oDiv2.div2T:'+oDiv2.div2T+' oDiv2.div2B:'+oDiv2.div2B);*/ //碰撞檢測 if(oDiv2.div2R<oDiv1.div1L || oDiv2.div2L>oDiv1.div1R || oDiv2.div2B<oDiv1.div1T || oDiv2.div2T>oDiv1.div1B){ //未傳送碰撞 }else{ //發生碰撞 alert('發生碰撞'); } } document.onmouseup=function (){ document.onmouseup=document.onmousemove=null; if(obj.setCapture) obj.releaseCapture(); } return false; } }
</script> </head> <body> <div id="div2">div2</div> <div id="div1">div1</div> </body> </html>