I am new to Roblox Lua and probably for most people, I have come to roadblocks. My friend and I are making a new game and I want the GUI to not feel static but lively. I designed the GUI frames and made an image button but I have written my own code to do it but keep on coming up with that the loops can overlap of you go back and forth very fast. I used "mouseEnter" and "mouseLeave" to detect it but I can't figure out how to stop the loop right when I leave it. I have spent many hours trying to figure it out but can't.
Here is my code:
local button = script.Parent
button.MouseEnter:Connect(function()
while true do
button.Rotation = 0
wait (.03)
button.Rotation = -1
wait (.03)
button.Rotation = -2
wait (.03)
button.Rotation = -3
wait (.03)
button.Rotation = -4
wait (.03)
button.Rotation = -5
wait (.03)
button.Rotation = -6
wait (.03)
button.Rotation = -7
wait (.03)
button.Rotation = -8
wait (.03)
button.Rotation = -9
wait (.03)
button.Rotation = -8
wait (.03)
button.Rotation = -7
wait (.03)
button.Rotation = -6
wait (.03)
button.Rotation = -5
wait (.03)
button.Rotation = -4
wait (.03)
button.Rotation = -3
wait (.03)
button.Rotation = -2
wait (.03)
button.Rotation = -1
wait (.03)
button.Rotation = 0
wait (.03)
button.Rotation = 1
wait (.03)
button.Rotation = 2
wait (.03)
button.Rotation = 3
wait (.03)
button.Rotation = 4
wait (.03)
button.Rotation = 5
wait (.03)
button.Rotation = 6
wait (.03)
button.Rotation = 7
wait (.03)
button.Rotation = 8
wait (.03)
button.Rotation = 9
wait (.03)
button.Rotation = 8
wait (.03)
button.Rotation = 7
wait (.03)
button.Rotation = 6
wait (.03)
button.Rotation = 5
wait (.03)
button.Rotation = 4
wait (.03)
button.Rotation = 3
wait (.03)
button.Rotation = 2
wait (.03)
button.Rotation = 1
wait (.03)
print ("hi")
end
end)
button.MouseLeave:Connect(function()
button.Rotation = 0
end)
The code can probably be shortened but I just need a way to figure out how to get the loop to stop right when the mouse leaves the GUI button.
SOLVED------- I took the code the given and worked with it for a bit, coming up with the following:
local button = script.Parent
local IsHovering = false
button.MouseEnter:Connect(function()
IsHovering = true
end)
button.MouseLeave:Connect(function()
IsHovering = false
end)
spawn(function()
while true do wait()
if IsHovering == true then
for count = 1,9,1 do wait(.03)
button.Rotation = count*-1
end
for count = 9,1,-1 do wait(.03)
button.Rotation = count*-1
end
for i = 1,9,1 do wait(.03)
button.Rotation = i
end
for i = 9,1,-1 do wait(.03)
button.Rotation = i
end
else
button.Rotation = 0
end
end
end)
Thanks for the code.

4 comments
First off, thank you. There is one issue though. When I tested this the rotations were a not as smooth as I wanted. If there is a way to tweak that can you tell me? Thanks a lot though.
Yeah you can tween them using Tween service
How exactly would I do that?
https://developer.roblox.com/en-us/api-reference/class/TweenService scroll to the code