How can I make a frame move when a key is pressed?

so i wanted to make a 2d game with screenguis but I got stuck on just trying to use enum and moving the frame of what key the press how can I do this?

You can use UserInputService:IsKeyDown

RunService.RenderStepped:Connect(function()
    if UserInputService:IsKeyDown(Enum.KeyCode.W) then
        print("Player is currently pressing the W key!")
    end
end)

I would say this :

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.E then
		game.Players.LocalPlayer.PlayerGui.ScreenGui.TextButton:TweenPosition(UDim2.new(0, 0, 0, 0))
	end
end)

I tested it, and it’s working.
Basically, if you want to move a gui, you have to use : myGui:TweenSize or TweenPosition(Udim2.new(0, 0, 0, 0))
In gui-tween, you have 2 numbers : the first 2 is the x, the last y is the y
If you wanna tween the x or the y, just say
local x = myGui.Position.X [- or +] Udim.new(number, number)
local y = myGui.Position.Y (same with the Y too)

myGui:TweenPosition(Udim2.new(x,y))

1 Like

You could have just placed the local script inside the text button instance you’re tweening.

His main game is a 2 Dimension experience, so I don’t see why it’s wrong in the startercharacterscripts.

local tweens = game:GetService("TweenService")
local cas = game:GetService("ContextActionService")

local frame = script.Parent

local function onArrowKeyPressed(actionName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin then
		if inputObject.KeyCode == Enum.KeyCode.W then
			local tween = tweens:Create(frame, TweenInfo.new(0.2), {Position = frame.Position - UDim2.fromScale(0, 0.1)})
			tween:Play()
		elseif inputObject.KeyCode == Enum.KeyCode.A then
			local tween = tweens:Create(frame, TweenInfo.new(0.2), {Position = frame.Position - UDim2.fromScale(0.05, 0)})
			tween:Play()
		elseif inputObject.KeyCode == Enum.KeyCode.S then
			local tween = tweens:Create(frame, TweenInfo.new(0.2), {Position = frame.Position - UDim2.fromScale(0, -0.1)})
			tween:Play()
		elseif inputObject.KeyCode == Enum.KeyCode.D then
			local tween = tweens:Create(frame, TweenInfo.new(0.2), {Position = frame.Position - UDim2.fromScale(-0.05, 0)})
			tween:Play()			
		end
	end
end

cas:BindAction("KeyPressed", onArrowKeyPressed, false, Enum.KeyCode.W, Enum.KeyCode.A, Enum.KeyCode.S, Enum.KeyCode.D)

Here’s an example script which moves a frame around whenever the “WASD” keys are pressed, in the expected direction (w for up, a for left, s for down and d for right).

Here’s the model file for reproduction purposes.

repro.rbxm (2.8 KB)

1 Like

this is what i was looking for thank you