Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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

This discussion is preserved as it was. New answers, comments, and votes are closed.