PcoWSkbVqDnWTu_dm2ix

Debounce – When and Why

Debounce – When and Why

5 min

A debounce system is a set of code that keeps a function from running too many times. It comes from the idea of mechanical switch bounce, where a pushed switch bounces and creates multiple signals. In Roblox, this problem occurs mainly with the BasePart/Touched event which fires every time a player’s body part contacts the detection part.

Common Case

Assume you want to build a hazardous trap part on the floor that causes 10 damage when touched. Code in a Script attached to the part may look like this:

The problem is that — because of how the physics engine handles collisions — the code will trigger multiple near-simultaneous events and cause more damage than intended.

To solve the problem, a debounce system can be included with a reset time as follows:

Alternatively to a local variable in the script, debounce can be managed by an articles/instance attributes|attribute directly on the object. For instance, the code below checks for a boolean IsTouched attribute on the trap part itself:

Other Uses

Beyond BasePart/Touched, debounce is useful for:

  • Preventing “button mashing” where a player might press an on-screen UI button repeatedly, before the button’s action has a chance to fully resolve.

  • Limiting how quickly a player can fire a weapon like a rocket launcher, effectively creating a “reload” time for the launcher before another rocket can be fired.

  • Preventing cumulative stacking of Tween|Tweens before the current tween has resolved.

Tags:
  • debounce
  • event
  • trigger