I’m working on a game with several abilities. I’m trying to create a script that handles input and runs the code of an ability assigned to the key the player presses. There is an ability that allows the player to jump higher by holding the Space key for 2 seconds. However, there is a problem, since I also want the player to do a normal jump by pressing the same key.
I tried looking for solutions and I could not find one. I wrote a script that checks the time elapsed from the moment the player started holding a key, but I was still scratching my head about telling a player pressing or holding a key apart.
Here is the code I managed to write so far:
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local holdingSpace = false
UserInputService.InputBegan:Connect(function(input, processed)
if processed then return end
if input.KeyCode == Enum.KeyCode.Space or input.KeyCode == Enum.KeyCode.ButtonA then
holdingSpace = true
end
end)
UserInputService.InputEnded:Connect(function(input, processed)
if processed then return end
if input.KeyCode == Enum.KeyCode.Space or input.KeyCode == Enum.KeyCode.ButtonA then
holdingSpace = false
end
end)
Try using ‘tick()’ to keep track of the amount of time the Space key was held down. I hope this points you in the right direction, but if you still need help let me know.
I wrote a script that checks the time elapsed from the moment the player started holding a key, but I was still scratching my head about telling a player pressing or holding a key apart.
I did just that, except I used os.clock().
The thing is, even with this knowledge, I don’t understand how to detect when a player presses a key and when a player holds a key.
I think this might be a game design question rather than a programming one. You’re trying to bind two separate events to a single action. Because pressing the jump key = holding it down. But if you really want to use the spacebar, usually what people do is connect it to a double jump. Those are easier to track and make more sense to the player
If you are still looking for a fix I did the same thing with the r key, I don’t have access to the script as of right now but I can post it later once I have access if you would like.
With a few small tests done I am 99% sure it is working but still haven’t done a full test