基于javascript实现碰撞检测
网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要为大家详细介绍了基于javascript实现碰撞检测,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了javascript实现碰撞检测的具体代码,供大家参考,具体内容如下
<html> <head> <style> #div1 {width:100px; height:100px; background:red; position:absolute; z-index:2;} #div2 {width:100px; height:100px; background:yellow; position:absolute; left:230px; :220px; z-index:1;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.οnlοad=function () { var oDiv=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); oDiv.οnmοusedοwn=function (ev) { var oEvent=ev||event; var disX=oEvent.clientX-oDiv.offsetLeft; var disY=oEvent.clientY-oDiv.offsetTop; document.οnmοusemοve=function (ev) { var oEvent=ev||event; oDiv.style.left=oEvent.clientX-disX+'px'; oDiv.style.=oEvent.clientY-disY+'px'; var l1=oDiv.offsetLeft;//红块左边线 var r1=oDiv.offsetLeft+oDiv.offsetWidth;//红块右边线 var t1=oDiv.offsetTop;//红块上边线 var b1=oDiv.offsetTop+oDiv.offsetHeight;//红块下边线 var l2=oDiv2.offsetLeft;//黄块左边线 var r2=oDiv2.offsetLeft+oDiv2.offsetWidth;//黄块右边线 var t2=oDiv2.offsetTop;//黄块上边线 var b2=oDiv2.offsetTop+oDiv2.offsetHeight;//黄块下边线 if(r1<l2 || l1>r2 || b1<t2 || t1>b2) { oDiv2.style.background='yellow'; } else { oDiv2.style.background='green'; } }; document.οnmοuseup=function () { document.οnmοusemοve=null; document.οnmοuseup=null; }; }; }; </script> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> </html>
碰撞检测原理图如上:
我们检测碰撞时,发现两个div碰上检测比没碰上的检测要难,所以以没碰上作为检测条件。画上九宫格,当红色div在黄色div左边线或是右边线或是上边线或是下边线外时是永远不可能碰上的,只要这四个条件都不满足,意味着两个div相撞了,将黄块变绿。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程