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

Why the character is walking diagnoly if hes not supposed to?

Asked by 10 years ago
local mouse = game.Players.LocalPlayer:GetMouse()
local h = game.Players.LocalPlayer.Character.Humanoid

mouse.KeyDown:connect (function (key)
    print(key)
    if key == "w" or key == "s" then
        h.WalkSpeed = 0
    elseif key == "a" or key == "d" then
        h.WalkSpeed = 16
    end
end)

What this script does is that avoids the player to walk forwards and backward, and SPECIFICLY left and right. It works perfectly. But if you hold "w" or "s" and hold "a" or "d" consecutively, your character starts walking diagnoly, wich as i said, the character can ONLY walk left and right. So please help me fix this script?

1 answer

Log in to vote
1
Answered by 10 years ago

KeyDown starts acting weird when you're trying to access multiple keys at once. The most effective way of combating this would be this:

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Humanoid = Player.Character.Humanoid
local Keys = {}
----------------------------------------------------------------------------
Mouse.KeyDown:connect(function(Key) Keys[Key] = true end)
Mouse.KeyUp:connect(function(Key) Keys[Key] = false end)
----------------------------------------------------------------------------
while true do
    if (Keys["w"] or Keys["s"])  then --If you are pressing the "w" or "s" key
        Humanoid.WalkSpeed = 0
    elseif (not (Keys["w"] or Keys["s"])) and (Keys["a"] or Keys["d"])) then --If you are ONLY pressing the "a" or "d" key
        Humanoid.WalkSpeed = 16
    end
    wait()
end
Ad

Answer this question