JS-Collision Detection and Collision Detection

Source: Internet
Author: User

JS-Collision Detection and Collision Detection

A simple Collision Detection example is used to check whether div1 is in conflict with div2. When div1 encounters div2, it changes the color of div2.


Take a look at the analysis diagram:


When div1 is active in a region above div2 (t2 ),

When div1 is active in the right line (r2) of div2 in the right area

When div1 is active in a region below div2 (b2 ),

When div1 is active in the left-side (r2) area of div2

In addition to the above four situations, other situations indicate that div1 and div2 have met, and the next interview will complete the test code

<div id="div1"></div><div id="div2"></div>
<style>        #div1{            width:100px ;height: 100px;background: green;            position: absolute;        }        #div2{            width:100px ;height: 100px;background: yellow;            position: absolute;left: 300px;top: 200px;z-index: -1;        }</style>
<Script> window. onload = function () {var oDiv = document. getElementById ('div1 '); var oDiv2 = document. getElementById ('div2'); var disX = 0; var disY = 0; oDiv. onmousedown = function (ev) {var ev = ev | window. event; disX = ev. clientX-oDiv. offsetLeft; disY = ev. clientY-oDiv. offsetTop; document. onmousemove = function (ev) {var ev = ev | window. event; var t1 = oDiv. offsetTop; var l1 = oDiv. offsetLeft; var r1 = oDiv. offsetLeft + oDiv. offsetWidth; var b1 = oDiv. offsetTop + oDiv. offsetHeight; var t2 = oDiv2.offsetTop; var l2 = oDiv2.offsetLeft; var r2 = oDiv2.offsetLeft + oDiv2.offsetWidth; var b2 = oDiv2.offsetTop + oDiv2.offsetHeight; if (b1 <t2 | l1> r2 | t1> b2 | r1 <l2) {// indicates not met} else {oDiv2.style. background = 'blue';} oDiv. style. left = ev. clientX-disX + 'px '; oDiv. style. top = ev. clientY-disY + 'px';} document. onmouseup = function () {document. onmousemove = null; document. onmouseup = null;} return false; }}</script>





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.