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

I have two identical scripts, but they function differently?

Asked by
B080 19
6 years ago

First version:

userInput.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.W then
        W = true
        if tick() - prev <= 0.2 then
            hum.WalkSpeed = 20
        end
        prev = tick()
    end
    if input.KeyCode == Enum.KeyCode.A then
        A = true
    end
    if input.KeyCode == Enum.KeyCode.S then
        S = true
    end
    if input.KeyCode == Enum.KeyCode.D then
        D = true
    end
end)

userInput.InputEnded:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.W then
        W = false
    end
    if input.KeyCode == Enum.KeyCode.A then
        A = false
    end
    if input.KeyCode == Enum.KeyCode.S then
        S = false
    end
    if input.KeyCode == Enum.KeyCode.D then
        D = false
    end
    if W == false and A == false and S == false and D == false then
        hum.WalkSpeed = 10
    end
end)

Second version:

function mov(input, key, var, bool)
    if input.KeyCode == key then
        var = bool
    end
end

userInput.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.W then
        W = true
        if tick() - prev <= 0.2 then
            hum.WalkSpeed = 20
        end
        prev = tick()
    end
    mov(input, Enum.KeyCode.A, A, true)
    mov(input, Enum.KeyCode.S, S, true)
    mov(input, Enum.KeyCode.D, D, true)
end)

userInput.InputEnded:Connect(function(input)
    mov(input, Enum.KeyCode.W, W, false)
    mov(input, Enum.KeyCode.A, A, false)
    mov(input, Enum.KeyCode.S, S, false)
    mov(input, Enum.KeyCode.D, D, false)
    if W == false and A == false and S == false and D == false then
        hum.WalkSpeed = 10
    end
end)

Basically what both versions should do is when you double tap the "W" key, you enable sprinting and are able to freely run around with WASD. It is disabled when you stop moving completely.

I thought they would both function the same, however, only the first version does what I wanted it to do. The second version never returns false so you end up running forever.

I just wanted to somehow shorten it. Is there a reason why it does this?

Answer this question