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

How do I actually check which keys are being used?

Asked by
Asigkem 32
7 years ago

This doesn't print Forward when I press W. How do I make it so it does? Never actually used CAS before.

01local contextAction = game:GetService("ContextActionService")
02 
03 
04function onKeyPress(actionName, userInputState, inputObject)
05    if userInputState == Enum.UserInputState.Begin then
06        if inputObject == Enum.KeyCode.W then
07            print('Forward')
08        end
09    elseif userInputState == Enum.UserInputState.End then
10        --nothing here yet
11    end
12end
13 
14contextAction:BindAction("keyPress", onKeyPress, false, Enum.UserInputType.Keyboard)

1 answer

Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

I'm pretty sure you used the wrong service. ContextActionServicebinds a set of inputs to a function. To bind a function to a keyboard button with this service, call the function BindAction. So, to print a string when the W key is pressed, a function can be bound like so:

1function onKeyPress(actionName, userInputState, inputObject)
2    if userInputState == Enum.UserInputState.Begin then
3        print("Forward")
4    end
5end
6 
7game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.W)

UserInputService binds functions to input via its events, such as InputBegan or InputEnded. These events fire on any input change, so it is important to check for the particular input you are interested in when handling the function. So, to print a string when the W key is pressed, a function can be bound like so:

1function onKeyPress(inputObject, gameProcessedEvent)
2    if inputObject.KeyCode == Enum.KeyCode.W then
3        print("Forward")
4    end
5end
6 
7game:GetService("UserInputService").InputBegan:connect(onKeyPress)

I think you needed to use UserInputService instead of ContextActionService. Try that. If it helped, upvote and accept answer. Thanks! (Snippets of code are from the wiki, same with the description on ContextActionService and UserInputService)

0
Ah right, okay. Thanks for this. I've never used these before, and the wiki is less than clear on how to use them. Asigkem 32 — 7y
0
No problem! PyccknnXakep 1225 — 7y
Ad

Answer this question