JSFiddle - React, Tailwind, and code Playground
by Chandana Thota
HTML
<div id="box">
</div>
<div id="box1">
</div>
<div id= "shooter">
</div>
<div id="bullet"></div>
CSS
#box{
position:absolute;
width:50px;
height:50px;
background-color:red;
left:-100px;
}
#box1{
position:absolute;
width:50px;
height:50px;
background-color:green;
}
#shooter{
position:absolute;
width:50px;
height:50px;
background-color:blue;
top:300px;
}
#bullet{
position:absolute;
width:30px;
height:30px;
border-radius:30px;
background-color:yellow;
top:300px;
}
JavaScript
//detecting divs collision
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var w1 = $div1.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var w2 = $div2.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
}
function loop() {
//moving first div from left to right
$('#box').css({left:0});
$( "#box" ).animate({ "left": "+=400px" }, 7000 , 'linear',
function() {loop();
})
//moving second div from left to right
$('#box1').css({left:"100px"});
$( "#box1" ).animate({ "left": "+=400px" }, 7000 , 'linear',
function() {loop();
})
}
loop();
$("#shooter").click(function(){
$('#bullet').css({top:"300px"});
$( "#bullet" ).animate({ "top": "-=350px" }, 5000 );
});
$(document).keydown(function(pk){
var pos = $('#shooter').position();
if(pk.keyCode == '37'){
$('#shooter').css('left',pos.left - 10 + 'px');
}
if(pk.keyCode == '39'){
$('#shooter').css('left',pos.left + 10 +'px');
}
});