您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JS实现碰撞检测步骤详解

2024/4/8 18:05:00发布20次查看
这次给大家带来js实现碰撞检测步骤详解,js实现碰撞检测的注意事项有哪些,下面就是实战案例,一起来看一下。
<!doctype html> <html> <head> <meta charset="utf-8"> <title> js碰撞检测</title> <style> p{width:100px;   height:100px; } #box{background:red; position:absolute; } #box1{background:green;position:absolute;top:300px; left:300px;} </style> <script> //两个碰撞的盒子。是建立在一个不动的基础上。所以可以根据不动的盒子求出四个方向的left和top值。然后再判断其是否碰撞,且碰撞的过程随时改变其层级,(原需 var 8个变量,现在只需4个变量) function colltext(obj,left,top,obj1){       var l1=obj.offsetleft-obj.offsetwidth;       var t1=obj.offsettop-obj.offsetheight;       var r1=obj.offsetleft+obj.offsetwidth;       var b1=obj.offsettop+obj.offsetheight;       if(left<l1||top<t1||left>r1||top>b1){         obj.style.zindex=3;         obj1.style.zindex=1;         return true;       }else{         obj.style.zindex=1;         obj1.style.zindex=3;         return false;       } }; window.onload=function(){   var obox=document.getelementbyid('box');   var obox1=document.getelementbyid('box1');   obox.onmousedown=function(ev){     var oevent= ev  ||  event;     var disx=oevent.clientx-obox.offsetleft;     var disy=oevent.clienty-obox.offsettop;     document.onmousemove=function(ev){       var oevent= ev ||  event;       var l=oevent.clientx-disx;       var t=oevent.clienty-disy;       obox.style.left=l+'px'  ;       obox.style.top=t+'px'  ;       if(colltext(obox1,l,t,obox)){         obox1.style.background='green';       }else{         obox1.style.background='yellow';       }     };     document.onmouseup=function(){       document.onmousemove=null;       document.onmouseup=null;       obox.reseasecapture&&obox.reseasecapture();     };     obox.setcapture&&obox.setcapture();     return false;   }   obox1.onmousedown=function(ev){     var oevent= ev ||  event;     var disx1=oevent.clientx-obox1.offsetleft;     var disy1=oevent.clienty-obox1.offsettop;     document.onmousemove=function(ev){       var oevent= ev ||  event;       var le=oevent.clientx-disx1;       var to=oevent.clienty-disy1;       obox1.style.left=le+'px'  ;       obox1.style.top=to+'px'  ;       if(colltext(obox,le,to,obox1)){         obox.style.background='red';       }else{         obox.style.background='#000';       }     };     document.onmouseup=function(){       document.onmousemove=null;       document.onmouseup=null;       obox1.reseasecapture&&obox1.reseasecapture();     }     obox1.setcapture&&obox1.setcapture();     return false;   } } </script> </head> <body> <p id="box"></p> <p id="box1"></p> </body> </html>
这里使用在线html/css/javascript运行工具http://tools.jb51.net/code/htmljsrun测试运行效果如下(碰撞判定时颜色改变):
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
react-navigation使用步骤详解
vue父子组件传值及slot应用步骤详解
以上就是js实现碰撞检测步骤详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product