Canvas score increments then clears

I want to update my score each time a collision occurs. The score correctly adds 1 and becomes Score: 1 for a frame and then goes back to 0. I can't figure out why the score is being cleared and reset to zero instead of incrementing during each collision.

// text
c.fillStyle = "#ffff00";
c.font = "30px Arial";
c.fillText("Score: 0 ", 10, 50);

var score = 0;
var scorevalue = 0;

// collision detection

if (dy >= 400 && (padxpos + 90 >= dx && padxpos <= 220)){
    t = 0;
    t += 0.1;
    dy = dyi + viy*t - (ay*t*t)/2;
    c.fillStyle = "#ffff00";
    c.font = "30px Arial";
    updateScore();
    }

// update score

function updateScore(){

    c.clearRect(0, 0, canvas.height, canvas.width);
    c.fillStyle = "#ff0000";
    c.fillRect(0, 0, canvas.width, canvas.height);
    c.fillStyle = "#ffff00";
    c.font = "30px Arial";
    scorevalue = ++score;
    c.fillText("Score: " + scorevalue, 10, 50);
    }

1 answer

  • answered 2018-11-12 03:43 physicsfrac

    In case anyone else stumbles across this same error...

    In the original fill text I had this

    c.fillText("Score: 0 ", 10, 50);
    

    so everytime the score updated c.filltext it was drawing the zero even though the score was properly incrementing. All I needed to do was fill the original text with the variable. Simple mistake that took forever to find.

    c.fillText("Score: " + scorevalue, 10, 50);