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

How would I get player if I were to press a button on the keyboard?

Asked by 5 years ago

I was wondering how I would be able to find player if I went and pressed a button like space or w. Im new to this type of scripting I would like to learn can someone please show me or explain to me how it works

1 answer

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

Roblox offers a service for this called the UserInputService. I'll explain how you use it.

UserInputService

The UserInputService is a service that, hence its name, is used for receiving input. The UserInputService is client-side only, so it can only be used in LocalScripts. There are two events that, in your case, you can use to detect keyboard input:

  1. InputBegan. This fires the input received (input) and a boolean named gameProcessedEvent that determines if the game internally observed the input. This is true only if the input is UI-related, such as mouse or touch input. With keyboard input, it returns false.
  2. InputEnded. Same as InputBegan except that the input parameter that is fired is the input that had ended, not the input that had started.

This is how you receive keyboard input (LocalScript):

local UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.Keyboard then -- Checks if the input was related to a keyboard
        if input.KeyCode == Enum.KeyCode.Zero then -- Checks if the key in the Enum was pressed. "Zero" can be any key you want.
            -- Do something
        end
    end
end)

Now, the input received on the client is from the LocalPlayer. So, in reality, the player who is giving input to the service happens to be the LocalPlayer on the client. To get that player, you just need to do game.Players.LocalPlayer. Pretty simple.

0
Thanks I understand it now and it really helps. voidofdeathfire 148 — 5y
Ad

Answer this question