How can I make the player only be able to move left and right?

I’m trying to make a 2D game and was wondering if there was a practical way to make it so that the player can only move left and right. My first idea was to put walls to make sure the player can’t move forwards or backwards. but that looks weird.

Any solutions would be appreciated!

1 Like

Using a new LocalScript, unbind moveBackwardAction and moveForwardAction.

game:GetService("ContextActionService"):UnbindAction("moveBackwardAction")
game:GetService("ContextActionService"):UnbindAction("moveForwardAction")

Make sure to disable shiftlock, which is a setting in StarterPlayer.

That works, but for mobile it doesn’t. I wanna make it work for all platforms.

I found that this post’s solution worked for mobile as well. Here’s the script, you can just replace the previous LocalScript code with this:

local player = game.Players.LocalPlayer
local RunService = game:GetService("RunService")
local ContextActionService = game:GetService("ContextActionService")

local jumping = false
local leftValue, rightValue = 0, 0

local function onLeft(actionName, inputState)
	if inputState == Enum.UserInputState.Begin then	
		leftValue = 1
	elseif inputState == Enum.UserInputState.End then
		leftValue = 0
	end
end

local function onRight(actionName, inputState)
	if inputState == Enum.UserInputState.Begin then
		rightValue = 1
	elseif inputState == Enum.UserInputState.End then
		rightValue = 0
	end
end

local function onJump(actionName, inputState)
	if inputState == Enum.UserInputState.Begin then
		jumping = true
	elseif inputState == Enum.UserInputState.End then
		jumping = false
	end
end

local function onUpdate()
	if player.Character and player.Character:FindFirstChild("Humanoid") then
		if jumping then
			player.Character.Humanoid.Jump = true
		end
		local moveDirection = rightValue - leftValue
		player.Character.Humanoid:Move(Vector3.new(moveDirection,0,0), false)
	end
end

RunService:BindToRenderStep("Control", Enum.RenderPriority.Input.Value, onUpdate)

ContextActionService:BindAction("Left", onLeft, true, "a", Enum.KeyCode.Left, Enum.KeyCode.DPadLeft)
ContextActionService:BindAction("Right", onRight, true, "d", Enum.KeyCode.Right, Enum.KeyCode.DPadRight)
ContextActionService:BindAction("Jump", onJump, true, Enum.KeyCode.Space, Enum.KeyCode.Up, Enum.KeyCode.DPadUp, Enum.KeyCode.ButtonA)

for mobile you will have to either remove it entirely like i did or make 2 custom buttons for left and right like in the game “Stud Bros.” i do not know how to make the moving part of the system but i do know you need to make your own

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.