[SOLVED] Triggering score once per object

Here’s the link to the editor: PlayCanvas | HTML5 Game Engine

Hello~ I am having an issue with finding how to collide with an object and having the score only increase once per object to avoid point spamming. This problem is really similar (almost identical) to another post I saw on here but our score counters are completely different and replicating their point counter has just led to errors on my end.

Thank you!

(Codes for scoring is in the poddCollision script)

Hey and Welcome, It seems collision is working well for you. For increasing the score only once, you can maybe add a differentiator that can differentiate whether the collided object has it’s point increased or not.

The simple solution is to add a tag on the incremented score’s object and when the next time it collides, you would be able to identify it easily.

Here is how you can add the tags on any entity.

this.entity.tags.add("PointAdded");

And here is how you check the entity tags

if (this.entity.tags.has("PointAdded")) {

}

Thanks for you help! I tried and it worked but checking the entity ended up not adding the point. So, I did this instead:

if (this.app.root.findByName('objName').tags.has('score')) {
            this.addPoint();
            this.app.root.findByName('objName').tags.remove('score');
} 

To detect collisions between two entities in PlayCanvas, you can use the collisionstart event. This event is fired when a collision occurs between two entities that have a collision component attached.

To avoid “point spamming” where the score is increased multiple times for the same object, you can add a boolean flag to the entity that gets set to true when the entity is first collided with. Then, you can check this flag in the collisionstart event and only increase the score if the flag is false.

Here’s some sample code that demonstrates this approach:

Example:

var PoddCollision = pc.createScript('poddCollision');

PoddCollision.prototype.initialize = function() {
    this.score = 0;
};

PoddCollision.prototype.onCollisionStart = function (result) {
    if (!result.other.entity.collided) {
        result.other.entity.collided = true;
        this.score++;
        console.log('Score: ' + this.score);
    }
};

In this code, we first initialize the score variable to 0 in the initialize method of the script.

Then, in the onCollisionStart method, we check if the collided flag on the other entity is false. If it is, we set the flag to true and increase the score by 1. We also log the score to the console for debugging purposes.

You can attach this script to the entity that you want to detect collisions with, and it should increase the score only once per collision. Don’t forget to add a collision component to the entity as well.