-
How to detect collision between two elements.
about 9 years ago
-
about 9 years ago
Hi, I have build a simplified example for you. I build a collide functionality by using jquery drag effect. Please go through below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Element Collision Testing</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script type="text/javascript"> $(document).ready(function(e) { $('.elem2').draggable({ //Start Drag Function drag: function(){ //Element 1 properties var elem1X = $('.elem1').offset().left; var elem1Y = $('.elem1').offset().top; var elem1Width = $('.elem1').width(); var elem1Height = $('.elem1').height(); //Element 2 properties var elem2X = $('.elem2').offset().left; var elem2Y = $('.elem2').offset().top; var elem2Width = $('.elem2').width(); var elem2Height = $('.elem2').height(); if (elem1X < elem2X + elem2Width && elem1X + elem1Width > elem2X && elem1Y < elem2Y + elem2Height && elem1Height + elem1Y > elem2Y ){ console.log("Elem 2 Div Collides "); $(this).css('background-color', 'yellow'); } else { $(this).css('background-color', 'blue'); } }//End Drag Function// }); });//Document Ready Function End// </script> <style type="text/css"> .elements { position:absolute; } .elem1 { width:50px; height:50px; background: red; top:5px; left:5px; } .elem2 { width:60px; height:40px; background: blue; top:60px; left:60px; } </style> </head> <body> <div style="width:80%; margin:0 auto; padding:5px 5px; border:2px solid #a9a9a9; position:relative;"> <div id="cr-stage" style="height:400px;"> <div class="elem1 elements"></div> <div class="elem2 elements"></div> </div> <p>Drag the second rectangle. Yellow background means collision, blue means no collision.</p> </div> </body> </html>
Use this code and I hope it will help you :)
1 Answer(s)