整理以前的文件时看到之前写过的圆形的碰撞检测,简单记录下。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="cav" width="500" height="500"></canvas> <script> var cav = document.getElementById('cav'), ctx = cav.getContext('2d'); var b1 = { r:40, x:100, y:100 }; var b2 = { r:40, x:165, y:100 }; function draw(){ for(var i=0; i<arguments.length; i++){ ctx.fillStyle = '#333'; ctx.beginPath(); ctx.arc(arguments[i].x,arguments[i].y,arguments[i].r,0,Math.PI*2); ctx.fill(); } } draw(b1,b2); function getBound(circle){ return{ x:circle.x - circle.r, y:circle.y - circle.r, w:circle.r*2, h:circle.r*2 } } function collision(c1,c2){ //如果碰撞了就返回true return !(c1.x + c1.w < c2.x || c1.y + c1.h < c2.y || c2.x + c2.w < c1.x || c2.y + c2.h < c1.y ); } var r = collision(getBound(b1),getBound(b2)); console.log(r); </script> </body> </html>