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

How do I actually check which keys are being used?

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

local contextAction = game:GetService("ContextActionService")


function onKeyPress(actionName, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		if inputObject == Enum.KeyCode.W then
			print('Forward')
		end
	elseif userInputState == Enum.UserInputState.End then
		--nothing here yet
	end
end
 
contextAction:BindAction("keyPress", onKeyPress, false, Enum.UserInputType.Keyboard)

1 answer

✓ Accepted answer

I'm pretty sure you used the wrong service. ContextActionService binds 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:

function onKeyPress(actionName, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		print("Forward")
	end
end
 
game.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:

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.W then
		print("Forward")
	end
end
 
game: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)

2 comments

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.

0

No problem!

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