Let’s say there’s a default number, 0. When the mouse is being clicked, no matter what the number is, it will add 1, then 1 second later, it will tween from 1 back to the default number (0). If the mouse is being clicked when it’s tweening back to 0 (Let’s say it was 0.4, add 1 then will be 1.4), after it will wait a second, it will tween from 1.4 to 0. And So on if it’s being clicked to multiple times. How do I do that with a simple and efficient way?
For loop is not necessary. (The following code is just an overview to the case and it doesn’t work.)
num = 0
mouse.Clicked:Connect(function()
num = num + 1
delay(1,function()
for i = num,0,-0.1 do
num = i
wait()
end
end)
end)
@Headstackk wants the numbers to be animated smoothly from 1 to 0. That gives player time to click on the button again and increment its amount.
In my opinion, a for loop is necessary. @Headstackk’s example code could work. You just have to place an if statement to check wether the value is being incremented while it is decrementing, and stop the current decrementing code to let the second code call to run.
But, I expect some slight errors that I can’t see in such an early stage.
And @Headstackk, you should probably increase the wait time too if you want the player to have time to click on the button
Feel free to ask any questions if the comments in my answer hasn’t helped.
local counter = {
num = 0; --> this is the starting number prior to any clicks
delayTime = 1; --> change this if you want it to wait longer
lastUpdate = 0; --> set by script when updated
threshold = 0.03; --> when lerping to 0, once it's reached to 'threshold' value it will decrease straight to 0
updated = Instance.new "BindableEvent"; --> event to handle updates
}
local lerp = (function (a, b, t)
return a + (b - a) * t
end)
--> Everytime we update the number we fire this event
--> Which will wait 1s before lerping the number to 0
--> In the meantime, or during the lerping, if the mouse is clicked again
--> the lerping will stop.
--> The process will continue again until there's no more input, or it's at 0
counter.updated.Event:connect(function ()
counter.lastUpdate = time()
delay(counter.delayTime, function ()
if time() - counter.lastUpdate >= 1 then
local cur = counter.num
local start = time()
while counter.num > 0 and time() - counter.lastUpdate >= 1 and time() - start <= 1 do
local nxt = lerp(cur, 0, time() - start)
counter.num = nxt < counter.threshold and 0 or nxt
wait()
end
end
end)
end)
mouse.Clicked:connect(function ()
counter.num = counter.num + 1
counter.updated:Fire()
end)
using a coroutine wrap you can run a thread side by side a function,
local duration = 1
num = 1
script.Parent.MouseButton1Down:Connect(coroutine.wrap(function()
for num = 1, 0, -0.1 do
if num<=0.1 then
num = 1
elseif num >0 then wait(.1) do
print(num)
end
end
end
end) )