Trap player to move in a specific z coordinates

Hello
I’m making a 2D game.
I want the player’s character to only move in the x and y-axis and never change the z-axis. But because physics keeps pushing the player in random coordinates when the player is running to a wall, it will break the game, so how can I fix this?

Images

What the player should be:


What player shouldn’t be(this bug was created when I ran into a perfectly smooth and perpendicular wall:

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

local Character = player.Character or player.CharacterAdded:Wait()
local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")
local TweenService = game:GetService("TweenService")
local Mouse = player:GetMouse()
local CurrentCamera = workspace.CurrentCamera




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, "w", Enum.KeyCode.Space, Enum.KeyCode.Up, Enum.KeyCode.DPadUp, Enum.KeyCode.ButtonA)

Thank you for reading!

Have you tried making 2d invisible barriers?

Maybe you can also try to just keep moving the player in the same Z axis.

1 Like

Yes, I tried and it sort of working but It will break my game quite a lot.

Can you tell me how? I don’t ask for an entire script, just a basic structure of the script.

I mean, can’t you just make a local script in the player that uses Heartbeat on RunService and continuesly set the humanoid root part to a specific Z axis?

It’s work! Thank you so much for your help!

1 Like

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