Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Coroutines waiting for random times?

shiftDown = false
momentum = 0
x = game:GetService("UserInputService")
x.InputBegan:connect(function(key)
	if key.KeyCode == Enum.KeyCode.LeftShift then
		shiftDown = true
		print("test")
		newThread2 = coroutine.create(function()
			repeat
				if momentum == 0 then
					momentum = 1
				end
				if momentum == 1 then
					humanoid.WalkSpeed = 20
					momentum = 2
				elseif momentum == 2 then
					humanoid.WalkSpeed = 32
				end
				wait(3)
			until shiftDown == false
		end)
		coroutine.resume(newThread2)
	end
end)
x.InputEnded:connect(function(key)
	if key.KeyCode == Enum.KeyCode.LeftShift then
		shiftDown = false
		wait()
		humanoid.WalkSpeed = 10
		momentum = 0
		print("Player stopped running from momentum "..momentum)
	end
end)

This script works fine, mostly. When you hold down shift for the first time, your walkspeed goes from 10 to 20. After 3 seconds, it goes from 20 to 32. This is as expected. Now, when you release shift and hold it down again, your walkspeed goes from 10 to 20 as expected... and then instead of waiting 3 seconds, it seems to wait a random amount of time before boostin your WalkSpeed to 32. I believe this is to do with how coroutines work, but I'm not entirely sure how they do.

1 answer

This discussion is preserved as it was. New answers, comments, and votes are closed.