码迷,mamicode.com
首页 > 其他好文 > 详细

碰撞检测

时间:2016-08-22 00:07:21      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>矩形碰撞01</title>
 6         <style type="text/css">
 7             * { margin: 0; padding: 0; }
 8             div { position: absolute; width: 100px; height: 100px; font-size: 50px; line-height: 100px; text-align: center; }
 9             #move_box { background-color: #40E0D0; cursor: pointer; }
10             #hit_box { left: 200px; top: 200px; background-color: #98FB98; }
11         </style>
12     </head>
13     <body>
14         <div id="move_box">移动</div>
15         <div id="hit_box">被撞</div>
16     </body>
17     <script type="text/javascript">
18 
19         var moveBox = document.getElementById("move_box");
20         var hitBox = document.getElementById("hit_box");
21         
22         //移动对象去进行碰撞
23         moveBox.onmousedown = function (event){
24             
25             var event = event || window.event;
26 
27             var disX = event.clientX - moveBox.offsetLeft;
28             var disY = event.clientY - moveBox.offsetTop;
29             
30             document.onmousemove = function (event){
31                 
32                 var event = event || window.event;
33                 
34                 var x = event.clientX - disX;
35                 var y = event.clientY - disY;
36                  
37                 var moveLeft = moveBox.offsetLeft;  //移动对象的左偏移
38                 var moveRight = moveLeft + moveBox.offsetWidth;  //移动对象的右偏移=左偏移+自身宽度
39                 var moveTop = moveBox.offsetTop;  //移动对象的上偏移
40                 var moveBottom = moveTop + moveBox.offsetHeight;  //移动对象的下偏移=上偏移+自身高度
41                 
42                 var hitLeft = hitBox.offsetLeft; //被撞对象的左偏移
43                 var hitRight = hitLeft + hitBox.offsetWidth;
44                 var hitTop = hitBox.offsetTop;
45                 var hitBottom = hitTop + hitBox.offsetHeight;
46                 
47                 if (moveBottom < hitTop || moveRight < hitLeft || moveTop > hitBottom || moveLeft > hitRight){
48                     hitBox.style.backgroundColor = "#98FB98";
49                     hitBox.innerHTML = "被撞";
50                 }else{
51                     hitBox.style.backgroundColor = "#FF6347";
52                     hitBox.innerHTML = "撞上";
53                 }
54                 
55                 moveBox.style.left = x + "px";
56                 moveBox.style.top = y + "px";
57             }
58 
59             //停止移动
60             document.onmouseup = function (){    
61                 document.onmousemove = null;
62             }
63 
64             return false;
65         }
66     </script>
67 </html>

 

碰撞检测

标签:

原文地址:http://www.cnblogs.com/PowellZhao/p/5793842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!