碰撞检测原理

一切的碰撞都是通过网页中x,y坐标来计算的,判断两个矩形是否发生碰撞,就是判断它们是否有重合部分。理论上是这样,但是实际上我们应该考虑什么时候不重合,因为这种逆向思维会简单很多,如果一味考虑什么时候重合,一般人很难理得清楚。所以我们先理清楚不重合的情况,那么反过来就是重合的情况了。

不重合的情况:
1.移动矩形在静止矩形的上方
2.移动矩形在静止矩形的下方
3.移动矩形在静止矩形的左边
4.移动矩形在静止矩形的右边

 

假如移动的矩形编号为1,静止的矩形编号为2;那么碰撞检测的JavaScript写法为:

  • var div1=document.getElementById("div1"),
  • left_1=div1.offsetLeft,
  • top_1=div1.offsetTop,
  • width_1=div1.offsetWidth,
  • height_1=div1.offsetHeight;
  •  
  • var div2=document.getElementById("div2"),
  • left_2=div2.offsetLeft,
  • top_2=div2.offsetTop,
  • width_2=div2.offsetWidth,
  • height_2=div2.offsetHeight;
  •  
  • var noConflict=left_1>left_2+width_2||left_1+width_1<left_2||top_1+height_1>top_2||top_1<top_2-height_2;
  • if(!noConflict){
  • //碰撞了,我要做点什么,比如说爆个炸啥的。
  • }

再说说圆形碰撞原理。

圆形因为没有了边角所以不能用矩形的碰撞原理,但可以通过及计算两个圆的中心距离与两个圆的半径之和的大小来判断是否有相交,如果有相交则碰撞了。看起来比矩形的还简单些,不过涉及到直角三角形的求边公式,小学数学知识派上用场了~

  • var div1=document.getElementById("div1"),
  • left_1=div1.offsetLeft,
  • top_1=div1.offsetTop,
  • width_1=div1.offsetWidth,
  • height_1=div1.offsetHeight,
  • point_x_1=left_1+width_1/2,
  • point_y_1=top_1+height_1/2;
  •  
  • var div2=document.getElementById("div2"),
  • left_2=div2.offsetLeft,
  • top_2=div2.offsetTop,
  • width_2=div2.offsetWidth,
  • height_2=div2.offsetHeight,
  • point_x_2=left_2+width_2/2,
  • point_y_2=top_2+height_2/2;
  •  
  • var distant= Math.sqrt(Math.pow(Math.abs(point_x_1-point_x_2),2)+Math.pow(Math.abs(point_y_1-point_y_2),2));
  • if(distant<width_1/2+width_2/2){
  • //碰撞了,我要做点什么,比如说爆个炸啥的。
  • }
posted @ 2017-08-24 09:39  \面朝阳光/  阅读(1915)  评论(0编辑  收藏  举报