[SOLVED] Health script not working

[SOLVED]
I made a health script for a box where every time it touches an entity with the tag of “bullet”, it decreases it health by 10. For some reason, it is not working.

Project link: PlayCanvas | HTML5 Game Engine

Code:

var Health = pc.createScript('health');
var health = 100

Health.prototype.initialize = function() {
    this.entity.collision.on('collisionstart', this.onCollisionStart, this);
};

Health.prototype.onCollisionStart = function (hit) {
    if (hit.other.tag === 'bullet') {
        health -= 10
    }   
};

Health.prototype.update = function(dt) {
    if (health === 0) {
        this.entity.destroy
    }
}

Solved:

[SOLVED]

try this

var Health = pc.createScript('health');

Health.prototype.initialize = function() {
    this.health = 100;
    this.entity.collision.on('collisionstart', this.onCollisionStart, this);
};

Health.prototype.onCollisionStart = function (hit) {
    if (hit.other.tags.has('bullet')) {
        this.health -= 10
        if (this.health === 0) {
            this.entity.destroy();
        }
    }   
};
1 Like

I will try.

Thanks very much for helping me fix my code. I’m new to PlayCanvas and JavaScript so I forgot to put the .has part.

1 Like

Make sure you check that the health is below one, not equal to zero, otherwise the health can easily become negative and therefore immortal.

1 Like

I will do that later.