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

Why does this key-hold not holding? You have to keep clicking for it to run.

Asked by 8 years ago
player = game.Players.LocalPlayer
local mouse = game.Players.LocalPlayer:GetMouse()
mouse.KeyDown:connect(function (key)
    for i, v in pairs(game.Players:GetChildren()) do
    if key == "f" then
    for i = 1,2 do
    if player.Magic.Value <= player.MagicMax.Value then
    player.Magic.Value = player.Magic.Value +1
    end
    end
    end
    end

    mouse.KeyUp:connect(function (key)
    if key == "f" then
    end
    end) 
    end)


This is the script. It has no errors. I don't know what I am doing wrong. What it is supposed to do is to increase the magic value as long as the f button is held. Instead it only increases the value by two and it does not continually do it until you let go of f. Instead you have to mash f for it to even go up.

0
(Replied) BlueTaslem 18071 — 8y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

Right now, your logic looks like this:

WHEN F FIRST PRESSED
    ADD TO MAGIC

... and that's all.

KeyDown only happens the moment that you begin pressing a key, and right now that's the only time you're adding magic.

This is the design you want:

EVERY MOMENT
    IF F IS CURRENTLY DOWN
        ADD TO MAGIC

The loop then looks like this:

while wait() do
    if F then
        player.Magic.Value = math.min(
            player.MaxMagic.Value,
            player.Magic.Value + 1)
    end
end

We simply have to set F to true when a KeyDown happens and false when a KeyUp happens.

Remember that these connections have to happen before the while loop

local F = false
mouse.KeyDown:connect(function(key)
    if key == "f" then
        F = true
    end
end)
mouse.KeyUp:connect(function(key)
    if key == "f" then
        F = false
    end
end)
0
Thank you so much! Relampago1204 73 — 8y
0
Problem. If i gain magic and then I stop, when i do it again my magic goes up faster Relampago1204 73 — 8y
0
The code that I have written does not do that. Can you post your full code, e.g. in a Hastebin link? BlueTaslem 18071 — 8y
0
sure Relampago1204 73 — 8y
View all comments (2 more)
0
The while loop goes AFTER the event code. It does not start or stop depending on the key events. Look at my code -- I do not have the while in the middle of the key functions. BlueTaslem 18071 — 8y
Ad

Answer this question