How to make a GUI button keep repeating code until it is released

I’m trying to make a D-Pad sort of control scheme for mobile on a game i’m working on (Has a custom character), but i don’t know how to make the character keep moving whilst i have the buttons pressed.

Here’s my code

MobileControls.Up.TouchLongPress:Connect(function(touchPositions, state)
	print(state)
	if state == Enum.UserInputState.Begin then
		repeat
			soul:TranslateBy(Vector3.new(0, 0, 0.5))
			wait(.025)
		until state == Enum.UserInputState.End 
	end
end)

MobileControls.Down.TouchLongPress:Connect(function(touchPositions, state)
	print(state)
	if state == Enum.UserInputState.Begin then
		repeat
			soul:TranslateBy(Vector3.new(0, 0, 0.5))
			wait(.025)

		until state == Enum.UserInputState.End 
	end
end)

MobileControls.Left.TouchLongPress:Connect(function(touchPositions, state)
	print(state)
	if state == Enum.UserInputState.Begin then
		repeat
			soul:TranslateBy(Vector3.new(-0.5, 0, 0))
			wait(.025)

		until state == Enum.UserInputState.End 
	end
end)

MobileControls.Right.TouchLongPress:Connect(function(touchPositions, state)
	print("touched!")
	print(state)
	if state == Enum.UserInputState.Begin then
		repeat
			soul:TranslateBy(Vector3.new(0.5, 0, 0))
			wait(.025)
			until state == Enum.UserInputState.End 
	end
end)

I can’t provide an actual answer since I have not touched mobile controls in a bit. But I will say there is some logical flaws I can spot.

If this function is ran once

MobileControls.Right.TouchLongPress:Connect(function(touchPositions, state)
	print("touched!")
	print(state)
	if state == Enum.UserInputState.Begin then
		repeat
			soul:TranslateBy(Vector3.new(0.5, 0, 0))
			wait(.025)
			until state == Enum.UserInputState.End 
	end
end)

How will it ever know that state changed if it was already called?

Your basically doing

local function something(state)
  repeat
    -- bla bla bla
  until state == "finished"
end
something("notfinished") -- This will never ever finish since its completely local.
something("finished") -- This will finish, but the past function will continue to run

If I’m understanding your logic correctly, something like this may better suite you.

local this = "water"
local function until_that(that)
  repeat
    -- bla bla bla
  until that == this
end
until_that("bottle")
this = "bottle"
-- Function should now stop since the local variable `this` was finally set.

In summary you may want to define some variables outside your :Connect() so the function running inside of :Connect can see the variable actively change.

Ohhhh. Yeah now that I think about it, that would work.

If that satisfies you with a good enough answer, don’t forget to mark as the solution!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.