So I have this piece of code that creates either a Mobile gui button or a key event that makes the player slow down when touched/called. I know the DRY principle but this code breaks it several times. It works well and doesn’t lag the game but I was hoping there was a way to make it a touch cleaner. If you guys know some cool function, coroutine, or something that I can use to fix this it would be much appreciated.
Was also planning to copy and redo this for a speed up button (simple variable/name changes)
local ContextActionService = game:GetService("ContextActionService") local player = game.Players.LocalPlayer local PlayerGui = player:WaitForChild("PlayerGui") local ScreenGui = PlayerGui:WaitForChild("ScreenGui") local TouchGui = PlayerGui:WaitForChild("TouchGui") local TouchControlFrame = TouchGui:WaitForChild("TouchControlFrame") local JumpButton = TouchControlFrame:WaitForChild("JumpButton") -- Get absolute size and position of button local absPositionX, absPositionY = JumpButton.Position.X, JumpButton.Position.Y player.Character.Humanoid.WalkSpeed = 350 state = 4 -- This records what speed the player is going at without calling on the player every time. --reset this l8r onewalk = 16 -- These record how fast the player will go at different states. You can change these and they change throughout the code. twowalk = 50 threewalk = 150 fourwalk = 350 local function SpeedDownbutton(actionName, inputState, inputObject) if inputState == Enum.UserInputState.Begin then if state == 1 then --do nothing end if state == 2 then player.Character.Humanoid.WalkSpeed = onewalk state = 1 end if state == 3 then player.Character.Humanoid.WalkSpeed = twowalk state = 2 end if state ==4 then player.Character.Humanoid.WalkSpeed = threewalk state = 3 end print(actionName, inputObject) print(player.Character.Humanoid.WalkSpeed) end end ContextActionService:BindAction("SpeedDownbutton", SpeedDownbutton, true, Enum.KeyCode.R, Enum.KeyCode.ButtonR1) ContextActionService:SetPosition("SpeedDownbutton", UDim2.new(0.7,absPositionX,0.2,absPositionY)) ContextActionService:SetTitle("SpeedDownbutton", "Speed Down")