Trying to calculate score on the basis of collision using collide() in p5.js

I am trying to calculate my game score using the collide() method from p5.play.js such that whenever the apple hits the hero, the score increments by one. Everything is working fine except the score. My score keeps on updating irrespective of the fact that the apple collides with the hero or not.

Here is my draw() function

function draw() {

background(backdrop);
drawSprite(hero);

for(i=0; i<apples.length; i++)
{
    apples[i].spr.collide(hero, scoreUpdate);

    if(cell[i] == 1 && previousGen[i] == 0)
    {
        apples[i].fall();
    }
    else if(cell[i] == 0 && previousGen[i] == 1 )
    {
        obstacles[i].fall();
    }
}

text("score: " + score, width-100, 20);
for(i=0; i<apples.length; i++)
{
    if(apples[i].spr.position.y > height)
    {
        generationEnd = true;
        apples[i].spr.position.y=100;
        obstacles[i].b.position.y=100;
    }
    else
    {
        generationEnd=false;
        break; 
    }
}


if(generationEnd==true)
    newGeneration();
}

And here is the scoreUpdate() function

function scoreUpdate(apple, hero)
{
   score++;
   apple.position.y = height+10;
 }

Can anybody help me fix this ? Thanks.

Tagged:

Answers

  • Answer ✓

    So I fixed it. The problem was that I was calling collide() function irrespective of the fact that the apple is falling or not. I called the collide function right after the apple was falling so it worked for some reason and it even sounds logical to check collision if the apple has fallen. Here is the updated draw() function

    function draw() {
    
    background(backdrop);
    drawSprite(hero);
    
    for(i=0; i<apples.length; i++){
    
        if(cell[i] == 1 && previousGen[i] == 0){
            apples[i].fall();
            apples[i].spr.collide(hero, scoreUpdate);
        }
        else if(cell[i] == 0 && previousGen[i] == 1 ){
            obstacles[i].fall();
        }
    
    }
    text("score: " + score, width-100, 20);
    for(i=0; i<apples.length; i++){
        if(apples[i].spr.position.y > height){
            generationEnd = true;
            apples[i].spr.position.y=100;
            obstacles[i].b.position.y=100;
        }
        else{
            generationEnd=false;
            break; 
        }
    }
    
    
    if(generationEnd==true)
        newGeneration();
    }
    
Sign In or Register to comment.