碰撞检测算法(2D矩形)
可能还有其他更加高效但复杂的算法用来进行碰撞检测,但下面的这个算法绝对是我见过最简单实用的。再次申明清楚,这个算法只适用于2D平面上的两个矩形之间的碰撞检测。
执行算法需要的信息
- 两个矩形的中心坐标(x,y)
- 两个矩形的长(width)
- 两个矩形的高(height)
直接给出代码
上图的两个两个矩阵分别称为blue和red,下面将利用HTML的canvas进行显示,并用JavaScript来编写碰撞检测算法代码。
<script>
function setup(){
var canvas = document.getElementById('MyCanvas');
if (canvas.getContext){
ctx = canvas.getContext('2d');
var red = {
x : 100,
y : 100,
width : 80,
height : 100
};
var blue = {
x : 160,
y : 180,
width : 100,
height : 130
};
// 碰撞检测(两行代码搞定)
if(
Math.abs(red.x - blue.x) < red.width/2 + blue.width/2 //横向判断
&&
Math.abs(red.y - blue.y) < red.height/2 + blue.height/2 //纵向判断
){
console.log("发生碰撞");
}
//rect的基准点是矩形的左上角
ctx.rect(red.x - red.width/2,red.y - red.height/2,red.width,red.height);
ctx.rect(blue.x - blue.width/2,blue.y - blue.height/2,blue.width,blue.height);
ctx.fill();
}
}
</script>
<html>
<head>
<style type="text/css">
canvas { background:#FAFAFA;}
</style>
</head>
<body onload="setup();">
<canvas id="MyCanvas" width="500" height="500"></canvas>
</body>
</html>