衝突検出のために、実際の境界矩形の位置を計算する必要があります。
var element1 = (document.getElementById('element1-id'));
var rect1 = element1.getBoundingClientRect();
次に、幅、高さ、左、および上部の位置を取得します
var left1= rect1.left;
var top1= rect1.top;
var width1= rect1.width;
var height1= rect1.Height;
次に、別のオブジェクト (この要素が衝突するオブジェクト) のプロパティを取得します。
var element2 = (document.getElementById('element2-id'));
var rect2 = element2.getBoundingClientRect();
幅、高さ、左、および上の位置を取得します
var left2= rect2.left;
var top2= rect2.top;
var width2= rect2.width;
var height2= rect2.Height;
衝突をチェックする時が来ました: 以下のメソッドをコードに貼り付けます:
function bounding_box_collision(b1_x, b1_y, b1_w, b1_h, b2_x, b2_y, b2_w, b2_h) {
if ((b1_x > b2_x + b2_w - 1) || // is b1 on the right side of b2?
(b1_y > b2_y + b2_h - 1) || // is b1 under b2?
(b2_x > b1_x + b1_w - 1) || // is b2 on the right side of b1?
(b2_y > b1_y + b1_h - 1)
) // is b2 under b1?
{
// no collision
return "No";
}
else// collision
{
return "Yes";
}
}
設定された間隔を実行し、必要な期間で衝突をチェックします。スムーズな衝突検出のために、以下のコードのように常に短い期間を使用します。
setInterval(function(){
if(( bounding_box_collision(left1, top1, width1, height1, left2, top2, width2, height2))=="Yes"){
console.log("Collision Detected");
}else{
console.log("No Collision");
}
},0)//0 milliseconds