Debounce: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>SoulStealer9875
No edit summary
m Text replacement - "</SyntaxHighlight>" to "</syntaxhighlight>"
 
(21 intermediate revisions by 4 users not shown)
Line 1: Line 1:
==Debounce==
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 switch bounces when pushed, creating multiple signals. In the context of ROBLOX, this problem occurs mainly with the [[Touched]] event, when a part touches another multiple times in a short space of time, but may be useful in other cases as well.
===What is Debounce?===
==Theory==
A '''Debounce''' system is a set of code that keeps a function from running too many times. It comes from the idea of someone bouncing against a wall and triggering an event many times. You don't always want your code to run again and again, so Debounces are used to keep this from happening.
 
===Theory===
Let's say you have a button on the floor. When you jump on the button, it prints a message to the output. Your code would look like this:
Let's say you have a button on the floor. When you jump on the button, it prints a message to the output. Your code would look like this:


{{Example|<pre>
<syntaxhighlight lang="lua">
function OnTouch(hit) --Creating the function
Workspace.Button.Touched:connect(function(hit)
print ("Button pressed") --Print the message
    print("Button pressed") --Print the message
wait(1) --Wait for 1 second
    wait(1)                 --Wait for 1 second
print ("Hi :D") --Print another message
    print("Hi :D")         --Print another message
end --Tells the function where to stop
end)
 
</syntaxhighlight>
game.Workspace.Button.Touched:connect(OnTouch) --Connect the Event to the Function
</pre>}}


This will put this message in the output:
This will put this message in the output:
<pre>
<syntaxhighlight lang="lua">
Button pressed
Button pressed
Hi :D
Hi :D
</pre>
</syntaxhighlight>
The problem is that the physics engine, because of the way bricks touch each other, will not register just one collision, it may cause several Touched events to fire. So your output will look more like this:
The problem is that because of the way the physics engine handles the collision, it will not register just one collision, but may cause several Touched events to fire, so your output will look more like this:
<pre>
<code>
Button pressed
Button pressed
Button pressed
Button pressed
Line 33: Line 28:
Hi :D
Hi :D
Hi :D
Hi :D
</pre>
</syntaxhighlight>
Rather than executing sequentially, all the event handlers execute at the same time.
 
Here is a possible scenario you may encounter:
 
If you're using a button to [[How to Make a Model Regenerate|regenerate a model]] then it will make 5 of whatever you are regenerating. This is an issue because ''all 5 will be in the same spot'' causing all kinds of problems. This can problem can easily be avoided by using a simple debounce system in your code. Of course, you could use a [[ClickDetector]] for your button, which would correct the problem, but you can't always use ClickDetectors, so sometimes, a debounce would be useful.
 
This is how a basic debounce system works:
 
When an action happens, such as someone pressing your floor button, the script '''locks''' any new function calls until a time passes or the action is complete.


Now if you're using a button for a [[How to Make a Model Regenerate|Regeneration Script]] then it will make 5 of whatever you are regenerating. This is an issue because ''all 5 will be in the same spot'' causing all kinds of problems. So you can see the problem when you have a script without Debounce.
==Use Case==
It's fairly simple to convert an existing script to using debounce. Let's use the same script we had above, and add a couple of lines. In this case we will put in a time limit to wait for until the function can be run again.


Debounce is a system that prevents this kind of problem. When an action happens, such as someone pressing your floor button, the script '''locks''' any new actions from that event until a time passes or the action is complete. It can be used for much more than just buttons, think of different ways you can use it for your scripts.
<syntaxhighlight lang="lua">
local buttonPressed = false
--Store whether the button is pressed in a local variable


===Use Case===
Workspace.Button.Touched:connect(function(hit)
It's fairly simple to convert an existing script to using debounce. Lets use the same script we had above, and add a couple of lines. In this case we will put in a time limit to wait for until the function can be run again.
    if not buttonPressed then
    -- Is it not pressed?


{{Example|<pre>
        buttonPressed = true
enabled = true
        -- Mark it as pressed, so that other handlers don't execute


function onTouch(hit)
        print("Button pressed")
    if not enabled then return end
        wait(1)
    enabled = false
        print("Hi :D")
    print("Button pressed")
        -- Do Stuff
    wait(1)
    print("Hi :D")
    enabled = true
end
game.Workspace.Button.Touched:connect(OnTouch)
</pre>}}


#The first line that we added was <code style="color:blue">enabled = true</code>. This line creates a [[Variables|global variable]] called '''enabled'''. This is the ''flag'' that we will use to let the function know if it is allowed to run or not.
        buttonPressed = false
#The second line <code style="color:blue">if not enabled then return end</code> is what's called a '''check'''. It '''checks''' to see if the script is allowed to run. <code style="color:blue">if</code> the function is <code style="color:blue">not</code> true (<code style="color:blue">enabled</code>) <code style="color:blue">then return</code> nothing and <code style="color:blue">end</code>.
        -- Mark it as not pressed, so other handlers can execute again
#The third line <code style="color:blue">enabled = false</code> sets the variable enabled to <code style="color:blue">false</code>. This ''flags'' the script, letting it know not to run. This is how the check works.
    end
#The fourth line <code style="color:blue">enabled = true</code> tells the script at the end of the function that it is ok to run the function again, because the function has ended. The ''flag'' is set to go.
end)
</syntaxhighlight>


This will cause your output to look like this:
This will cause your output to look like this:
<pre>
<code>
Button pressed
Button pressed
Hi :D
Hi :D
</pre>
</syntaxhighlight>


That's more like it! You can use this same concept, by adding the same 4 lines to different scripts, in most any script involving functions. It doesn't even have to just be touched objects, it can be used to keep people from pressing a button more than once, firing a weapon more often than you want, or preventing a new event from happening before the old one is done. Take a look at the next example.
That's more like it! You can use this same concept, by adding the same 4 lines to different scripts, in most any script involving functions. It doesn't even have to just be touched objects, it can be used to keep people from pressing a button more than once, firing a weapon more often than you want, or preventing a new event from happening before the old one is done. Take a look at the next example.


===Real World===
==Real World==


Here's the Local Gui script of the Rocket Launcher tool:
Here's the Local Gui script of the Rocket Launcher tool:


{{Example|<pre>
<syntaxhighlight lang="lua">
enabled = true
enabled = true
function onButton1Down(mouse)
function onButton1Down(mouse)
if not enabled then
    if not enabled then
return
        return
end
    end


enabled = false
    enabled = false
mouse.Icon = "rbxasset://textures\\GunWaitCursor.png"
    mouse.Icon = "rbxasset://textures\\GunWaitCursor.png"


wait(12)
    wait(12)
mouse.Icon = "rbxasset://textures\\GunCursor.png"
    mouse.Icon = "rbxasset://textures\\GunCursor.png"
enabled = true
    enabled = true


end
end
</pre>}}
</syntaxhighlight>


When you fire a rocket, the script shows the reload icon. Then the function waits for 12 seconds. During this time, enabled is false, so if the player tries to fire another rocket, the script won't run because the function will just return right away. After the 12 seconds are up, the reload cursor goes away and enabled becomes true again, allowing the user to fire another rocket.
When you fire a rocket, the script shows the reload icon. Then the function waits for 12 seconds. During this time, enabled is false, so if the player tries to fire another rocket, the script won't run because the function will just return right away. After the 12 seconds are up, the reload cursor goes away and enabled becomes true again, allowing the user to fire another rocket.
==Advanced notation==
After a while, it might get tedious defining a separate debounce variable for each event handler. Instead, you can write a debounce function, that returns a debounced copy of its first argument.
<syntaxhighlight lang="lua">
function debounce(func)
    local isRunning = false    -- Create a local debounce variable
    return function(...)      -- Return a new function
        if not isRunning then
            isRunning = true
            func(...)          -- Call it with the original arguments
            isRunning = false
        end
    end
end
</syntaxhighlight>
Applying this to the original code:
<syntaxhighlight lang="lua">
Workspace.Button.Touched:connect(debounce(function(hit)
    print("Button pressed") --Print the message
    wait(1)                --Wait for 1 second
    print("Hi :D")          --Print another message
end))
</syntaxhighlight>


[[Category:Scripting Tutorials]]
[[Category:Scripting Tutorials]]

Latest revision as of 06:05, 27 April 2023

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 switch bounces when pushed, creating multiple signals. In the context of ROBLOX, this problem occurs mainly with the Touched event, when a part touches another multiple times in a short space of time, but may be useful in other cases as well.

Theory

Let's say you have a button on the floor. When you jump on the button, it prints a message to the output. Your code would look like this:

Workspace.Button.Touched:connect(function(hit)
    print("Button pressed") --Print the message
    wait(1)                 --Wait for 1 second
    print("Hi :D")          --Print another message
end)

This will put this message in the output:

Button pressed
Hi :D

The problem is that because of the way the physics engine handles the collision, it will not register just one collision, but may cause several Touched events to fire, so your output will look more like this: Button pressed Button pressed Button pressed Button pressed Button pressed Hi :D Hi :D Hi :D Hi :D Hi :D </syntaxhighlight> Rather than executing sequentially, all the event handlers execute at the same time.

Here is a possible scenario you may encounter:

If you're using a button to regenerate a model then it will make 5 of whatever you are regenerating. This is an issue because all 5 will be in the same spot causing all kinds of problems. This can problem can easily be avoided by using a simple debounce system in your code. Of course, you could use a ClickDetector for your button, which would correct the problem, but you can't always use ClickDetectors, so sometimes, a debounce would be useful.

This is how a basic debounce system works:

When an action happens, such as someone pressing your floor button, the script locks any new function calls until a time passes or the action is complete.

Use Case

It's fairly simple to convert an existing script to using debounce. Let's use the same script we had above, and add a couple of lines. In this case we will put in a time limit to wait for until the function can be run again.

local buttonPressed = false
--Store whether the button is pressed in a local variable

Workspace.Button.Touched:connect(function(hit)
    if not buttonPressed then
    -- Is it not pressed?

        buttonPressed = true
        -- Mark it as pressed, so that other handlers don't execute

        print("Button pressed")
        wait(1)
        print("Hi :D")
        -- Do Stuff

        buttonPressed = false
        -- Mark it as not pressed, so other handlers can execute again
    end
end)

This will cause your output to look like this: Button pressed Hi :D </syntaxhighlight>

That's more like it! You can use this same concept, by adding the same 4 lines to different scripts, in most any script involving functions. It doesn't even have to just be touched objects, it can be used to keep people from pressing a button more than once, firing a weapon more often than you want, or preventing a new event from happening before the old one is done. Take a look at the next example.

Real World

Here's the Local Gui script of the Rocket Launcher tool:

enabled = true
function onButton1Down(mouse)
    if not enabled then
        return
    end

    enabled = false
    mouse.Icon = "rbxasset://textures\\GunWaitCursor.png"

    wait(12)
    mouse.Icon = "rbxasset://textures\\GunCursor.png"
    enabled = true

end

When you fire a rocket, the script shows the reload icon. Then the function waits for 12 seconds. During this time, enabled is false, so if the player tries to fire another rocket, the script won't run because the function will just return right away. After the 12 seconds are up, the reload cursor goes away and enabled becomes true again, allowing the user to fire another rocket.

Advanced notation

After a while, it might get tedious defining a separate debounce variable for each event handler. Instead, you can write a debounce function, that returns a debounced copy of its first argument.

function debounce(func)
    local isRunning = false    -- Create a local debounce variable
    return function(...)       -- Return a new function
        if not isRunning then
            isRunning = true

            func(...)          -- Call it with the original arguments

            isRunning = false
        end
    end
end

Applying this to the original code:

Workspace.Button.Touched:connect(debounce(function(hit)
    print("Button pressed") --Print the message
    wait(1)                 --Wait for 1 second
    print("Hi :D")          --Print another message
end))