[SOLVED] Increment Score Every Second - Code Not Functioning

Hello everyone,

I am trying to increase the score by one each second. However, it just increments once, and doesn’t change after that. At the lose event, the score is supposed to be alerted. The problem is shown in the recording below.

My code is as follows.

CollideOff.prototype.initialize = function() {
    
    this.score = 0;
    
    this.timer = 0;
    
    this.entity.collision.on('collisionstart', this.onCollisionStart, this);
    
};

// update code called every frame
CollideOff.prototype.update = function(dt) {
    
    this.timer += dt;
    
    if (this.timer >= 1) {
        this.score ++;
        this.timer =0;
    }
    
};

This is for incrementing.

if (result.other.name === "SpinningBallLeft") {
        this.entity.enabled = false;
        
        if (this.ObjectType === 'death') {
            this.app.root.findByName('part_burst3').particlesystem.reset();
            this.app.root.findByName('part_burst3').particlesystem.play();
            this.app.fire("camera:shake");
            
            setTimeout(function (){this.app.root.findByName("Game_Over").enabled = true;}.bind(this), 1000);
            alert(this.score);
            
        }

This is for alerting. Note - full code is not given above, so pardon missing brackets.

EDITOR - https://playcanvas.com/editor/scene/874865

How can I continue?

Your code is fine, the big issue here is that every one of balls has a new CollideOff script - meaning that every ball will have its own score. Because they only take about second to fall down and hit you, your score will always be 1.

I’d recommend creating one script attached to your Root (or similar) that keeps track of time & score.

1 Like

But I would need to use events then correct? To show the score when the player dies?

Yep! You can do something like this.app.on('player:death', this.onPlayerDeath, this); in your score script, and then this.app.fire('player:death'); in your collideOff script.

1 Like

I’ll try it out and get back to you.

ScoreKeeper.prototype.update = function(dt) {
    this.timer += dt;
    
    if (this.timer >= 1) {
        this.score ++;
        this.timer =0;
    }
};

Where would I add the necessary line @davidpox? Never really used pc events before…

Put it in your Initialize function. Then create another function called onPlayerDeath and you can do whatever you want in there.

Something like this:

ScoreKeeper.prototype.initialize = function() {
    this.app.on('player:death', this.onPlayerDeath, this);
};

ScoreKeeper.prototype.update = function(dt) {
    this.timer += dt;
    
    if (this.timer >= 1) {
        this.score ++;
        this.timer =0;
    }
};

ScoreKeeper.prototype.onPlayerDeath = function() {
    // do whatever here
};
1 Like

Thanks a lot for your help!

1 Like