Advertisement
bitetti

Fast Rectangle Intersection Test

Jan 18th, 2012
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html>
  2.   <head>
  3.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  4.     <title>Fast Rect Intersection Test</title>
  5.  
  6.     <style type="text/css">
  7. #debug {
  8.     width: 100%;
  9.     height: 50px;
  10.     position: fixed;
  11.     background: #ffffa0;
  12. }
  13.  
  14. .box {
  15.     position: absolute;
  16.     top: 120px;
  17.     left: 120px;
  18.     width: 50px;
  19.     height: 50px;
  20.     border: 1px solid #aaa;
  21. }
  22.     </style>
  23.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  24.     <script type="text/javascript">
  25.     <!-- //
  26.  ;
  27. function Rec(ob)
  28. {
  29.     this.lf = ob.offset().left;
  30.     this.tp = ob.offset().top;
  31.     this.rt = this.lf + ob.width();
  32.     this.bt = this.tp + ob.height();
  33.    
  34.     // this is te core of implementation
  35.     // a scalar test
  36.     this.checkCollision = function( rec )
  37.     {
  38.         if (this.bt >= rec.tp )
  39.             if (this.tp <= rec.bt)
  40.                 if (this.rt >= rec.lf)
  41.                     if (this.lf <= rec.rt)
  42.                         return true;
  43.         return false;
  44.     };
  45.    
  46.     this.toString = function()
  47.     {
  48.         return "["+ this.lf + "," + this.rt + "," + this.tp + "," + this.bt + "," +"]"
  49.     };
  50.     return this;
  51. }
  52.  
  53. function mouseMove(e)
  54. {
  55.     var s = $("#seeker");
  56.     s.css("top", e.pageY - s.height()*.5).css("left", e.pageX - s.width()*.5);
  57.     var r = new Rec(s);
  58.    
  59.     $("#debug").html( String((r.checkCollision(r2)) ? "true" : "false") + " " + e.pageX + " " + e.pageY + " " + r.toString());
  60. }
  61.  
  62. var r2;
  63.  
  64. function ini()
  65. {
  66.     r2 = new Rec($("#col1"));
  67.     $(window).mousemove(mouseMove);
  68. }
  69.  
  70. $(window).ready(ini);
  71.     // -->
  72.     </script>
  73.   </head>
  74.   <body>
  75. <div id="debug"></div>
  76. <div class="box" id="col1"></div>
  77. <div class="box" id="seeker"></div>
  78.   </body>
  79. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement