[SOLVED] setInterval for Damage intervals to player?

hello! i wanted to make my player take -1 HEART every time she is in contact with the Wall. i tried using
this.entity.collision.on('contact', this.onCollisionStart, this);
but it racks up way too fast on contact (collisionstart only runs the code once and does no further damage), so i was thinking of only letting the code run in 3 second intervals. it was difficult for me to find information relevant to my situation so im hoping for some help.
i learned that setInterval does not work with this so i would have no idea how to work around it. below is the code in my Wall’s Score.prototype.onCollisionStart

if (result.other.name == 'Yue') {
        //play when hit wall
        //and deal damage to player
        health -=1;
        var hearts = this.app.root.findByName('HeartDisplay');
        hearts.element.text = health.toString();

help is much appreciated! thank you.
project link: PlayCanvas | HTML5 Game Engine


setInterval/setTimeout is tricky, since it will execute even when the tab is minimized or not in focus. It can be used but even better is to use your own timer inside your scripts update method.

Check this post on how to get started in measuring time, you can use this timer then to apply damage after a cooldown period has finished.

1 Like

thanks so much Leonidas! this was exactly what i needed. much appreciated :grin:

to those that lurk the forums (like me) i used the linked post above’s timer code, and in my onCollisionStart i had this to activate it.

//if the player hits the wall
if (result.other.name == 'Player') {
        //activate timer code in update
        this.isTimerActive = true;
1 Like