I’m encountered a roadblock in my code. I’ve tried multiple different things but none of them have helped solved anything.
Expected result: (When R is pressed and held once)
Problem: (When R is spammed then held)
The code:
local holdingR = false
local rotatingHeartbeat
userInputService.InputBegan:Connect(function(input)
if (input.KeyCode == Enum.KeyCode.R) then
print("R")
yOrientation += rotValue
holdingR = true
local holdingTime = 0 -- creating new holdingTime each time
while holdingR do
if (holdingTime >= 5 and placing) then
break
else
holdingTime += 1
wait(.15)
end
end
if (holdingTime >= 5 and placing) then
print("Starting heartbeat")
rotatingHeartbeat = runService.Heartbeat:Connect(function() -- heartbeat runs multiple times. I assume it's because holdingTime is not nil when input ended.
yOrientation += rotValue
end)
end
return
end
end)
userInputService.InputEnded:Connect(function(input)
if (input.KeyCode == Enum.KeyCode.R) then
holdingR = false
if rotatingHeartbeat then
rotatingHeartbeat:Disconnect()
end
print("R Stopped")
end
end)
So far I’ve tried placing holdingTime outside of the input, made no difference.
I’d appreciate any direction on what the problem might be.
You can use an id system to differentiate between separate button presses:
local r_id
local rotatingHeartbeat
userInputService.InputBegan:Connect(function(input)
if (input.KeyCode == Enum.KeyCode.R) then
print("R")
yOrientation += rotValue
-- I changed this part
local currentId = newproxy() -- create a new symbol
r_id = currentId
local holdingTime = 0 -- creating new holdingTime each time
while r_id == currentId do
if (holdingTime >= 5 and placing) then
break
else
holdingTime += 1
wait(.15)
end
end
if (holdingTime >= 5 and placing) then
print("Starting heartbeat")
rotatingHeartbeat = runService.Heartbeat:Connect(function() -- heartbeat runs multiple times. I assume it's because holdingTime is not nil when input ended.
yOrientation += rotValue
end)
end
return
end
end)
userInputService.InputEnded:Connect(function(input)
if (input.KeyCode == Enum.KeyCode.R) then
r_id = nil -- also changed this
if rotatingHeartbeat then
rotatingHeartbeat:Disconnect()
end
print("R Stopped")
end
end)
This will probably not fix all your problems, but at least it fixes your current one.
The simplest possible fix for this in my opinion was is to switch your logic with the variable holdingR and just do
local rotValue = 1
local DELAY_TIME = 0.15
userInputService.InputBegan:Connect(function(inputObject, gameProcessed)
if gameProcessed then
return
end
if inputObject.KeyCode == Enum.KeyCode.R then
while userInputService:IsKeyDown(inputObject.KeyCode) do
yOrientation += rotValue
wait(DELAY_TIME)
end
end
end)