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

How do I trigger a player action by pressing a key on a keyboard?

Alright so like in some games like for expample in Kohltastrophe's Realm when you Hold R it makes your player summon whatever your element is. How would you script that? Like you hold a key and your character goes into an animation while a part is changing in color size position etc. . . I just don't have any Idea what so ever. Please help!

2 answers

Using the Player:GetMouse() function, it is possible to listen for key events. Here is an example script (Put it in a local script !)

local Player = Game.Players.LocalPlayer
local Mouse = Player:GetMouse()
Mouse.KeyDown:connect(function(Key)
 	if Key == "e" then
		print("E pressed")
	end
end)

A simple approach would be to create a key api for which you can read - writing is done by some core code. Lets take a look.

local KeyAPI = {}

KeyAPI.Keys = {} 
-- Stores: index = key (byte)
-- value = {[1] = (up = 1 OR down = 0), [2] = time (seconds since last state change)}

function KeyAPI.GetKeyCode(key)
	return key:byte()
end

function KeyAPI.KeyIsUp(key)
	local index = KeyAPI.GetKeyCode(key)
	if KeyAPI.Keys[index] then
		return KeyAPI.Keys[index][1] == 1
	end
	return false
end

function KeyAPI.KeyIsDown(key)
	local index = KeyAPI.GetKeyCode(key)
	if KeyAPI.Keys[index] then
		return KeyAPI.Keys[index][1] == 0
	end
	return false
end

function KeyAPI.KeyIsUpFor(key, time)
	if KeyAPI.KeyIsUp(key) then
		local index = KeyAPI.GetKeyCode(key)
		return (tick() - KeyAPI.Keys[index][2]) > time
	end
	return false 
end

function KeyAPI.KeyIsDownFor(key, time)
	if KeyAPI.KeyIsDown(key) then
		local index = KeyAPI.GetKeyCode(key)
		return (tick() - KeyAPI.Keys[index][2]) > time
	end
	return false 
end	

local mouse = game.Players.LocalPlayer:GetMouse()
mouse.KeyDown:connect(function(key)
	KeyAPI.Keys[self.GetKeyCode(key)] = {0, tick()}
end)
mouse.KeyUp:connect(function(key)
	KeyAPI.Keys[self.GetKeyCode(key)] = {1, tick()}
end

KeyIsDown: returns if the key is down KeyIsUp: returns if the key is up KeyIsDownFor: returns if the key is down for time (seconds) KeyIsUpFor: returns if the key is up for time(seconds)

Example usage (sprinting when w is down longer than 3 seconds and a tool is equipped)

	local tool = script.Parent
	tool.Equipped:connect(function()
		repeat
			wait()
		until KeyAPI.KeyIsDownFor("w", 3)
		game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 24
		wait(2)
		if game.Players.LocalPlayer.Character.Humanoid.WalkSpeed == 24 then
			game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
		end
	end)

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