您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)原生js怎么實(shí)現(xiàn)碰撞檢測(cè)的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
具體內(nèi)容如下
隨手寫了個(gè)簡(jiǎn)單的碰撞檢測(cè)的代碼。檢測(cè)box1和box2是否發(fā)生碰撞,若發(fā)生碰撞,box2顏色發(fā)生隨機(jī)改變,并反彈到隨機(jī)位置。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box1,.box2{ width: 100px; height: 100px; background-color: #f00; position:absolute; } .box2{ background-color: #00f; left: 200px; top: 200px; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> <script> var box1=document.querySelector(".box1"); var box2=document.querySelector(".box2"); box1.addEventListener("mousedown",mouseHandler); function mouseHandler(e){ if(e.type==="mousedown"){ e.preventDefault(); document.elem=this; document.pointX= e.offsetX; document.pointY= e.offsetY; document.addEventListener("mousemove",mouseHandler); this.addEventListener("mouseup",mouseHandler); }else if(e.type==="mousemove"){ this.elem.style.left= e.x-this.pointX+"px"; this.elem.style.top= e.y-this.pointY+"px"; hitText(this.elem,box2); }else if(e.type==="mouseup"){ document.removeEventListener("mousemove",mouseHandler); this.removeEventListener("mouseup",mouseHandler); } } function hitText(elem1,elem2){ var rect1=elem1.getBoundingClientRect(); var rect2=elem2.getBoundingClientRect(); var ponit1={x:rect1.x,y:rect1.y}; var ponit4={x:rect1.x+rect1.width,y:rect1.y+rect1.height}; if( ponit4.x>rect2.x &&ponit1.x<(rect2.x+rect2.width) &&ponit4.y>rect2.y &&ponit1.y<(rect2.y+rect2.height)){ elem2.style.backgroundColor=randomColor(); elem2.style.left=Math.round(Math.random()*document.documentElement.clientWidth)+"px"; elem2.style.top=Math.round(Math.random()*document.documentElement.clientHeight)+"px"; } } function randomColor(){ var a=Math.round(Math.random()*255); var b=Math.round(Math.random()*255); var c=Math.round(Math.random()*255); var color="rgb("+ a+","+b+","+c+")"; return color; } </script> </html>
感謝各位的閱讀!關(guān)于“原生js怎么實(shí)現(xiàn)碰撞檢測(cè)”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。