How to debounce pointer input events?

I’ve got a Phaser3 and React project where I’d like to display text in a React element when the cursor is over a sprite in the phaser canvas, then have it disappear when cursor moves out. I have it working, but the performance tanks, because of repeated calls on the “pointerover” event. Is there a way to have the pointerover and pointerout events fire once? I’ve tried using the “once” event but I need it to occur more than once, just one event firing at a time. Can I reassign the once events after they’ve fired once?

Here’s what I have working:

game.input.on("pointerover", (event, gameObjects) => {
	mouseHoverOn(event, gameObjects, game);
});

export function mouseHoverOn(event, gameObjects, game, canFire) {
	const name = store.getState().flowers.byId[gameObjects[0].id].name;
	const posX = event.event.clientX;
	const posY = event.event.clientY;
	const data = { posX, posY, name };
	store.dispatch(showTooltip(data));
}

Full Repo: https://github.com/nodes777/flower-game-phaser3

Thank you!

Unfortunately, we have a ‘pointerout’ event but no matching ‘pointerin’. That would make this super simple. But we can essentially simulate it.

This is probably how I would handle this:

let isPointerIn = false;
game.input.on("pointerover", (event, gameObjects) => {
    if (isPointerIn) {
         return;
    }
	mouseHoverOn(event, gameObjects, game);
    isPointerIn = true;
});

game.input.on("pointerout", (event, gameObjects) => {
	isPointerIn = false;
});

Maybe not the most elegant solution but it works and should keep things running efficiently. I am not aware of any built-in debouncing features.

1 Like

Thanks for your help! Hmm, I thought that should work too. But I’m getting the same issue. I think it has to do with something I’m doing in React now. The performance still tanks, and there’s a bundle of DOM events on a single mouse over. I’m not sure how to go about fixing this. I may have to rethink the structure of the functionality and display it inside Phaser using a text element or something.

Thank you!

Hmm…it may be that just firing these events are causing problems. If you can’t find a way to clean it up from the React side, what you could do is just drop down to a lower level, leave the pointer events alone and handle it in more of a game-loop way, where you just do bounds checking for when the mouse touches the border of the object you want to mousein to, fire your logic once and then run a mouseout type logic when the user touches the border again (which would be when it is leaving the object).

Using the update loop, there are several different ways you could approach this. Hopefully, though, you can find the root cause of what is causing the problem so you can keep using the events since that is obviously the easiest to maintain.

1 Like