I'm making a small game in javascript, eggs are falling and when it hit the basket I want to to send the eggs to its initial state and increase the score but my collision function not working, I'm new to javascript and it hasn't been a month since I start learning it so I don't know a lot.
What I have tried:
these the variables
var basket = document.getElementById("basketDiv");
var basketScore = document.getElementById("basketScore");
var egg1 = document.getElementById("egg1");
var egg2 = document.getElementById("egg2");
var egg3 = document.getElementById("egg3");
var egg = document.getElementsByClassName("egg");
var scoreInp = document.getElementById("Score");
var score = Number(scoreInp.innerHTML);
here i looping over the eggs since var egg return array-like
for(var i=0;i<egg.length;i++){
if(checkEggHitsTheBasket(egg[i]))
{
setEggIntialState(egg[i]);
dropdownEggs(egg[i]);
}
here is my collision function i also tried in the if condition to check if they aren't collisend but also not working
function collision(div1,div2){
var rectX1_left = div1.offsetLeft;
var rectY1_top = div1.offsetTop;
var rectHeight1 = div1.offsetHeight;
var rectWidth1 = div1.offsetWidth;
var rect1_bottom = rectY1_top + rectHeight1;
var rect1_right = rectX1_left + rectWidth1;
var rectX2_left = div2.offsetLeft;
var rectY2_top = div2.offsetTop;
var rectHeight2 = div2.offsetHeight;
var rectWidth2 = div2.offsetWidth;
var rect2_bottom = rectY2_top + rectHeight2;
var rect2_right = rectX2_left + rectWidth2;
if(rect1_right>rectX2_left &&rectX1_left<rect2_right&&
rect1_bottom > rectY2_top&& rectY1_top <rect2_bottom){
return true;
}
else {
return false;
}
}
here i chechk if they are collisened
function checkEggHitsTheBasket(egg){
if(collision(egg,basket)){
score++;
scoreInp.innerHTML=score;
basketScore.innerHTML=score;
}
}
and also the eggs and basket they have position absolute and the left attribute by %, not px is it okay?