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
Roblox offers a service for this called the UserInputService
. I'll explain how you use it.
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:
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.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.