The code to detect collisions is quite simple, although it requires making some previous assumptions:
- Both elements are rectangular (or can be considered rectangles). As in your case they are DIVs there will be no problems with this.
- Both elements must be contained in the same "positioned father": this is so that when asking the position of each element, it is always relative to the same reference system (his father).
- You only need to detect collisions between two elements. If there are more than two (but not too many!) You can detect collisions by pairs of objects .
Basically, two elements to and b collide if these four conditions are met at the same time:
The left side of a is to the left of the right side of b .
The right side of a is on the right side of the left side of
b .
The bottom side of a is below the top side of
b .
The upper side of a is on the lower side of
b .
Of course, depending on what you want to verify, the four inequalities can be strict ( <
) or not ( <=
)
$(document).keyup(function(event) {
//alert(event.keyCode)
if(event.keyCode == 39){
$(".caja1").css({"left":"+=50px"})
DetectarColision()
}
if(event.keyCode == 37){
$(".caja1").css({"left":"-=50px"})
DetectarColision()
}
});
function DetectarColision(){
/// "a" y "b" deben ser dos objetos HTMLElement
var a = $(".caja1");
var b = $(".caja2");
var a_pos = {t : a.position().top,
l: a.position().left,
r: a.position().left + a.width(),
b: a.position().top + a.height()};
var b_pos = {t : b.position().top,
l: b.position().left,
r: b.position().left + b.width(),
b: b.position().top + b.height()};
//Detecta si se superponen las áreas
if( a_pos.l <= b_pos.r && a_pos.r >= b_pos.l
&& a_pos.b >= b_pos.t && a_pos.t <= b_pos.b ){
console.log('colision');
}
}
div.caja1, div.caja2 {
width: 100px;
height: 100px;
position: absolute;
}
div.caja1 {
background: rgb(83, 53, 117)
}
div.caja2 {
right:100px;
background:rgb(56, 199, 70)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="caja1">
caja 1
</div>
<div class="caja2">
caja 2
</div>