Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I make a localscript recognize when I've pressed a key?

Asked by 5 years ago

I'm ultimately trying to make a localscript that prevents the player from using the W and S keys to move forward and backward (platform game). For now, though, I'm trying to get the concept of just getting a script to recognize when these keys are pressed. My goal with this specific script is to make it print "q off" and "q on" when I press the Q key.

I probably did this all wrong because I'm new to Lua, but I gave it my best shot. No error messages, but it doesn't work. The following code is in a local script.

local player = game.Players.LocalPlayer
deb = false
input = game:GetService("UserInputService")
actionkey = Enum.KeyCode.Q

function pressQ(key)
    if key == actionkey and deb == false then
        print("q on")
        deb = true
    end
    if key == actionkey and deb == true then
        print("q off")
        deb = true
    end
end

input.InputBegan:Connect(pressQ)

Thanks for any help!

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

InputObjects


The first parameter of InputBegan is the input object, which isn't a keycode enum. However, it does have a KeyCode Property that can be used for this purpose.

local player = game.Players.LocalPlayer
local deb = false
local input = game:GetService("UserInputService")
local actionkey = Enum.KeyCode.Q

local function pressQ(key,gpe)
    if gpe then return end
    if key.KeyCode == actionkey  then
        if deb then 
            print("q off")
            deb = false
        else
            print("q on")
            deb = true
        end 
    end
end

input.InputBegan:Connect(pressQ)

Some other minors things here:

  • You didn't change deb back to false after checking if it was true, thus it will always print "q off"

  • you should really use local variables here

  • InputBegan has a 2nd parameter , that is the game processed event boolean, which is true if the key has been used for something else before that specific InputBegan event. It can be used to tell whether if the player in question is typing (one example of how it can be used)

0
I made the changes you suggested (thanks so much), but it's still not working when I test it in Studio. Any ideas? Flannelling 4 — 5y
0
hmm theking48989987 2147 — 5y
0
there might be other factors at play here theking48989987 2147 — 5y
0
try using remote events DeceptiveCaster 3761 — 5y
0
MC, could you answer this question with an example of how to use remote events? I've never coded with one before. Flannelling 4 — 5y
Ad

Answer this question