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

How do I allow the part to keep moving if the key is down?

At the moment, you have to press the "W" key each time to move one stud, however. I want it so if you hold the W key down, the part will keep going forward until the key is not being held anymore. Any ideas on how to fix this?

game:GetService("UserInputService").InputBegan:connect(onKeyPress)
local UserInputService = game:GetService("UserInputService")
local LetterW = Enum.KeyCode.W
local function IsLetterDown()
	return UserInputService:IsKeyDown(LetterW) 
end
local function Input(input, gameProcessedEvent)
	if not IsLetterDown() then
		wait(1)
	else
		if FreeCam == true then -- The variables for FreeCam are already set.
			game.Workspace.Camera.Blobby.Position = Vector3.new(game.Workspace.Camera.Blobby.Position.X+1, game.Workspace.Camera.Blobby.Position.Y, game.Workspace.Camera.Blobby.Position.Z)
		end
	end
end

Thank you.

2 answers

local UserInputService = game:GetService("UserInputService") --The service we will be using to detect inputs.

local Blobby = workspace.Camera:WaitForChild("Blobby") --"Blobby", the part that we will be moving.
local ButtonIsDown = false --The variable we will be using to define if the W button is down or not.

local InputBegan = function(Key) --The function for when an input begins.
    if Key.KeyCode == Enum.KeyCode.W then --If the input is "Enum.KeyCode.W", which is obviously the W key, then:
        ButtonIsDown = true --Set ButtonIsDown to true.
    end
end

local InputEnded = function(Key) --The function for when an input ends.
    if Key.KeyCode == Enum.KeyCode.W then --If the input being released is "Enum.KeyCode.W", which is obviously the W key, then:
        ButtonIsDown = false --Set ButtonIsDown to false.
    end
end

UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputEnded:Connect(InputEnded)

while wait() do --An infinite loop to make sure that Blobby keeps moving everytime ButtonIsDown is true.
    if ButtonIsDown then --If the W key is being held, then:
        Blobby.Position = Vector3.new(Blobby.Position.X + 1, Blobby.Position.Y, Blobby.Position.Z) --Move Blobby's X position by 1 stud.
    end
end

You should try this instead.

3 comments

0

Sorry but this didn't quite work.

0

How did it not work? I have tested it in Studio and it did work.

0

anybody reading this?

So while infinite loops are generally frowned upon, I believe in this case it would be beneficial.

if keyIsPressed then
    while true do
        --camera movement
        if keyReleaseDetected then
            break
        end
    end
end

It would cut down on the input lag due to only needing to check for the keypress once.

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