js里面的碰撞检测。。。。。。。。。

这一段代码里,我想要方块在堆积到顶端以后就会停止下落(希望在原代码上修改)

var cvs=document.getElementById("canvas") var cxt=cvs.getContext("2d") var gravity=0.5 var colors=new Array("#00BFFF","#FFFF00","#FF8C00","#AB82FF","#008B8B") var rects=new Array() var temp=creatRect() window.requestAnimationFrame(drawFrame,cvs) function drawFrame(){ window.requestAnimationFrame(drawFrame,cvs) cxt.clearRect(0,0,cvs.width,cvs.height) temp.vy+=gravity temp.y+=temp.vy if(temp.y+temp.height>cvs.height){ temp.y=cvs.height-temp.height temp=creatRect() } for(var i=0;i<rects.length;i++){ drawRect(rects[i]) } } function creatRect(){ var temp=new Rect() temp.lineWidth=1 temp.color=colors[Math.round(Math.random()*(colors.length-1))] temp.width=Math.round(Math.random()*30+20) temp.height=Math.round(Math.random()*30+20) temp.x=Math.round(Math.random()*(cvs.width-temp.width)) temp.y=0 rects.push(temp) return temp } function drawRect(rect){ if(temp!=rect&&hitTest(temp,rect)){ temp.y=rect.y-temp.height temp=creatRect() } rect.draw(cxt) } function hitTest(rectA,rectB){ return!(rectA.x+rectA.width<rectB.x||rectB.x+rectB.width<rectA.x||rectA.y+rectA.height<rectB.y||rectB.y+rectB.height<rectA.y) }

这个是script里面的方法

<!DOCTYPE html>




<br> #canvas{<br> border:slateblue solid 2px;<br> background: white;<br> }<br>





<br> var cvs=document.getElementById(&quot;canvas&quot;)<br> var cxt=cvs.getContext(&quot;2d&quot;)<br> var gravity=0.5<br> var colors=new Array(&quot;#00BFFF&quot;,&quot;#FFFF00&quot;,&quot;#FF8C00&quot;,&quot;#AB82FF&quot;,&quot;#008B8B&quot;)<br> var rects=new Array()<br> var temp=creatRect()<br> window.requestAnimationFrame(drawFrame,cvs)<br> function drawFrame(){<br> window.requestAnimationFrame(drawFrame,cvs)<br> cxt.clearRect(0,0,cvs.width,cvs.height)<br> temp.vy+=gravity<br> temp.y+=temp.vy<br> if(temp.y+temp.height&gt;cvs.height){<br> temp.y=cvs.height-temp.height<br> temp=creatRect()<br> }<br> for(var i=0;i&lt;rects.length;i++){<br> drawRect(rects[i])<br> }</p> <pre><code> } function creatRect(){ var temp=new Rect() temp.lineWidth=1 temp.color=colors[Math.round(Math.random()*(colors.length-1))] temp.width=Math.round(Math.random()*30+20) temp.height=Math.round(Math.random()*30+20) temp.x=Math.round(Math.random()*(cvs.width-temp.width)) temp.y=0 rects.push(temp) return temp } function drawRect(rect){ if(temp!=rect&amp;&amp;hitTest(temp,rect)){ temp.y=rect.y-temp.height temp=creatRect() } rect.draw(cxt) } function hitTest(rectA,rectB){ return!(rectA.x+rectA.width&lt;rectB.x||rectB.x+rectB.width&lt;rectA.x||rectA.y+rectA.height&lt;rectB.y||rectB.y+rectB.height&lt;rectA.y) } &lt;/script&gt; &lt;/body&gt; </code></pre> <p></html></p>

图片说明
图片说明
图片说明

图片说明

drawFrame函数的window.requestAnimation()放在函数地步,然后检测碰撞之后不就return 不要执行这个一步就行了。
顺带说一句,提问也是一门技术活,你是什么需求,到了哪一步,遇见了什么问题,尝试过什么问题,关键代码是什么。