How would i prevent people from spamming animations

im currently trying to write my own sprite sheet character thing, but people are able to spam keys and bug the animations out really weirdly. this is the first time i’ve made something like this really and there are no errors at all in the output so i have no idea what i’m doing wrong. yes ive tried using debounce and waiting, but nothing seems to be working? i am really confused as to why this is happening and i really need help for a working solution :frowning: .


in the video i walked foward with S key, then i walked backward with W key. oddly enough when i spam both of those keys (or just spam any of wasd in general) the animations play both at once and bug out

uis = game:GetService("UserInputService")
rs = game:GetService("RunService")
lp = game:GetService("Players").LocalPlayer
lc = lp.Character or lp.CharacterAdded:Wait()
body = lc:WaitForChild("lp")
you = body.b.i
playing = false
curranim = nil
debounce = false

local anims = {
	WalkFront = {Vector2.new(0,0), Vector2.new(84,-6), Vector2.new(0,0), Vector2.new(84,126)},
	WalkBack = {Vector2.new(168,0), Vector2.new(252,-6), Vector2.new(168,0), Vector2.new(252,126)},
	IdleFront = {Vector2.new(0,0)},
	IdleBack = {Vector2.new(0,0)},
}

local function stopcurranim()
	if playing and curranim then
		playing = false
	end
end
local function play(animname, animspeed)
	stopcurranim()
	local anim = anims[animname]
	if not anim then return end
	playing = true
	curranim = animname
	while playing do
		for _, frame in ipairs(anim) do
			if not playing then break end
			you.ImageRectOffset = frame
			print(frame)
			task.wait(animspeed)
		end
	end
	curranim = nil
	playing = false
end

spawn(function()
play("IdleFront", .5)
end)
uis.InputBegan:Connect(function(k,gpe)
if gpe then return end
if k.KeyCode == Enum.KeyCode.W and not debounce then
debounce = true
stopcurranim()
task.wait(.15)
play("WalkBack",.3)
elseif k.KeyCode == Enum.KeyCode.S and not debounce then
debounce = true
stopcurranim()
task.wait(.15)
play("WalkFront",.3)
end
end)

uis.InputEnded:Connect(function(k,gpe)
	if gpe then return end
	if k.KeyCode == Enum.KeyCode.W then
	stopcurranim()
	debounce = false
	elseif k.KeyCode == Enum.KeyCode.S then
	stopcurranim()
	debounce = false
	end
end)
1 Like

Consider simplifying your animation system to just play one animation on RenderStepped, so that it’s only possible for one to play. Your setup here where the animations are running in while loops with task.wait() calls inside anonymous functions bound to UIS is just a nightmare scenario for trying to synchronously handle user input. Go with the K.I.S.S. approach and just change the curranim to the latest and update it every frame. Like 70% of this code will just be simplified away because all the ‘debounce’ flags and things are just bandaids on the real problem, that your system allows running animations concurrently.

2 Likes