This time I will give you an example of how to use JS to determine collisions. There are many application scenarios for collision, such as setting off fireworks, small balls bouncing off walls, pixel birds, etc., so we must first figure out how to determine collision before we can proceed with future operations.
HTML page code:
<p id="d1"></p> <p id="d2"></p>
CSS page code:
<style type="text/css"> *{ padding: 0px; margin: 0px; } #d1{ width: 100px; height: 100px; background: red; position: absolute; } #d2{ width: 200px; height: 200px; background: yellow; position: absolute; top: 200px; left: 400px; position: absolute; } </style>
JS page code:
<script type="text/javascript"> p=document.querySelectorAll("p"); function hit(obj){ obj.onmousedown=function(e){ var e=e||window.event; var dX=e.offsetX; var dY=e.offsetY; document.onmousemove=function(e){ var x=e.clientX; var y=e.clientY; obj.style.left=x-dX+"px"; obj.style.top=y-dY+"px"; if(p[0].offsetTop+p[0].offsetHeight>=p[1].offsetTop && p[0].offsetTop<=p[1].offsetTop+p[1].offsetHeight && p[0].offsetLeft+p[0].offsetWidth>=p[1].offsetLeft && p[0].offsetLeft<=p[1].offsetLeft+p[1].offsetWidth){ console.log("你撞我了!再撞一个试试!") }; } document.onmouseup=function(){ document.onmousemove=null; } } } hit(p[0]); hit(p[1]); </script>
This article explains how to determine collision through JS. For more related content, please pay attention to the php Chinese website.
Related recommendations:
Introducing some js implementation solutions for classic algorithms
javascript Set as homepage and add to favorites JS code
Understanding of inheritance in JS
The above is the detailed content of Implement the method of determining collision through JS!. For more information, please follow other related articles on the PHP Chinese website!