Faizy Posted May 8, 2017 Share Posted May 8, 2017 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 More sharing options...
Abhishek Singhal Posted May 8, 2017 Share Posted May 8, 2017 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') } Faizy 1 Link to comment Share on other sites More sharing options...
Faizy Posted May 8, 2017 Author Share Posted May 8, 2017 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 More sharing options...
Abhishek Singhal Posted May 8, 2017 Share Posted May 8, 2017 Would this serve the purpose ?? var goalLineCrossed = false; if (player.x > goalline.x) { if(!goalLineCrossed){ goalLineCrossed = true; console.log('crossed') } else{ // Do something else } // Do continuous task here } Faizy 1 Link to comment Share on other sites More sharing options...
Faizy Posted May 8, 2017 Author Share Posted May 8, 2017 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 More sharing options...
Abhishek Singhal Posted May 8, 2017 Share Posted May 8, 2017 Yes, you should have a look at "Phaser.Signal" this can be used to trigger events and you may also call signal.fireOnce , to do the exact thing only once. Link to comment Share on other sites More sharing options...
Recommended Posts