Hello!
Currently I’m trying to make a simple 2D movement using UI’s
I’m trying to move the character sprite to the left but it work works every time you press the ‘A’ key instead of holding it down.
Could I get any help? Heres the code /
uiplayer = {
plr = script.Parent.MainGame.Ground.player,
movement_y = 0.001,
movement_x = 0.001,
spd = 2 --cannot be 1 or 0 (or else player will not move)
}
plr = game.Players.LocalPlayer
uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(key, gp)
print("Key Pressed")
if key.KeyCode == Enum.KeyCode.A then
print("Key Pressed")
uiplayer.plr.Position = UDim2.fromScale(uiplayer.plr.Position.X.Scale -uiplayer.movement_x * uiplayer.spd, uiplayer.plr.Position.Y.Scale)
end
end)
You can check if a key is being held down by using a while loop.
Didn’t work.
Here’s the code I might have done something wrong
while true do
wait(0.2)
uis.InputBegan:Connect(function(key, gp)
print("Key Pressed")
if key.KeyCode == Enum.KeyCode.A then
print("Key Pressed")
uiplayer.plr.Position = UDim2.fromScale(uiplayer.plr.Position.X.Scale -uiplayer.movement_x * uiplayer.spd, uiplayer.plr.Position.Y.Scale)
end
end)
end
Use the InputEnded
event to check if the key was unpressed.
uis.InputEnded:Connect(function(key, gp)
print("Key Unpressed")
if key.KeyCode == Enum.KeyCode.A then
print("Key Unpressed")
uiplayer.plr.Position = --position
end
end)
1 Like
uiplayer = {
plr = script.Parent.MainGame.Ground.player,
movement_y = 0.001,
movement_x = 0.001,
spd = 2 --cannot be 1 or 0 (or else player will not move)
}
plr = game.Players.LocalPlayer
uis = game:GetService("UserInputService")
local keyPressed = false
uis.InputBegan:Connect(function(key, gp)
if gp then return end
if key.KeyCode == Enum.KeyCode.A then
keyPressed = true
while keyPressed do wait()
print("Key Pressed")
uiplayer.plr.Position = UDim2.fromScale(uiplayer.plr.Position.X.Scale -uiplayer.movement_x * uiplayer.spd, uiplayer.plr.Position.Y.Scale)
end
end
end)
uis.InputEnded:Connect(function(key)
if key.KeyCode == Enum.KeyCode.A then
keyPressed = false
end
end)
2 Likes
Yes, but Before I add that I just want to test to see if it will move to the left. And If that works then I would add InputEnded to make it stop moving.
This code will error, you need a time break between each iteration of the loop.
Studio stopped responding as I ran the code.
You need a time break between each iteration of the while loop.
Could I add a wait to the loop?
Yes, that is what I meant by break.