Click here to Skip to main content
15,671,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
JavaScript
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; //left
    var rectY1_top = div1.offsetTop;   //top
    var rectHeight1 = div1.offsetHeight;
    var rectWidth1 = div1.offsetWidth;
    var rect1_bottom = rectY1_top + rectHeight1; // bottom
    var rect1_right = rectX1_left + rectWidth1;  //right

    var rectX2_left = div2.offsetLeft; //left
    var rectY2_top = div2.offsetTop;  //top
    var rectHeight2 = div2.offsetHeight;
    var rectWidth2 = div2.offsetWidth;
    var rect2_bottom = rectY2_top + rectHeight2; //bottom
    var rect2_right = rectX2_left + rectWidth2;  //right

    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?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900