Search code examples
inputluauser-inputsimulationroblox

Roblox Lua Script, It is possible to simulate a key being pressed?


I'm making a game to play with my friends which uses others people scripts/mechanics and in theses scripts has a key bind set to a specific key which is "Q" and one of my friends play on console which he can't do that action which is the main core of my game.

I've search it everywhere and nothing, I found about VirtualUser but it only works for command bar.

Is there any other way to achieve this?


Solution

  • It is not possible to simulate a key press.

    However, you can bind the logic that is executed when the key is pressed to also fire with controller input as well. Take a look at the docs for ContextActionService:BindAction.

    The BindAction function accepts a few arguments :

    • actionName : a string to uniquely identify the action
    • functionToBind : a function that will get called when that action is dispatched
    • createTouchButton : a boolean, when true will create a button on touch devices like phones and tablets
    • inputTypes : a tuple of all of the different keys to listen for

    So you can use this to bind multiple inputs, including controller input, to the same logic as what happens when you would press the letter q. For example ...

    local ContextActionService = game:GetService("ContextActionService")
    
    local function handleAction(actionName, inputState, inputObject)
        if actionName == "DoThing" then
            if inputState == Enum.UserInputState.Begin then
                print("Time to do the thing")
            end
        end
    end
     
    -- Do a thing when the user presses q or the Y Button on a controller
    ContextActionService:BindAction("DoThing", handleAction, true, Enum.KeyCode.Q, Enum.KeyCode.ButtonY)
    

    For more information, see...