Jump to content

Execute something exactly one time


Faizy
 Share

Recommended Posts

Hey,

let´s assume a player and a finish line. As soon as the player crosses the finish line, the console should say 'crossed'.

 

When I would set up something like this in the update function, I will get the result every time the function fires. 

if (player.x > goalline.x) {
console.log('crossed')
}

 

Is there a way to add something like a listener to the player which updates the positions and checks the condition, but will only fire the function once?

 

Im sure there are multiple ways to solve this, most likely in the update function and one outside(something like an event listener). Could someone help me out? :)

Link to comment
Share on other sites

Hi Faizy,

I believe you are running a check for the condition withing the update function or any other function that is being called continuously.
The solution in this case could be to create a flag or a variable like goalLineCrossed and updating it as follows :

var goalLineCrossed = false;

if ((player.x > goalline.x) && !goalLineCrossed)
{
   goalLineCrossed = true;
    console.log('crossed')
}

Link to comment
Share on other sites

Thank you Abhishek Singhal

However I need something that checks the position of player.x all the time  but will only execute the given code when the condition occur. I´m looking for something that checks the position all the time throughout the game and will fire a function once.

Link to comment
Share on other sites

Ah, I got it now! Thank you :)

 

function updateScore() {
    main.pipes.children.forEach(function(element, index) {
        if ( (element.x < main.bird.x) && (element.crossed == false) ) {
            console.log('Scored')
            element.crossed = true;
        }
    })
}

 

But, non-related to everything above, is there a way to add a listener to a sprite for example who checks if a given condition happend and executes given code(something like an 'event' in phaser)?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...