Optimizing moving script because it's too laggy

I have this code in my game picks up key inputs from the client side (just keys WASD) and replicate movement on the server side. However the issue is that the script is simply TOO LAGGY when there’s more than one players. Nothing I have tried so far really works to reduce lag…

The code looks something like this:

--//Client Side
local RS = 	game:GetService("ReplicatedStorage")
local UIS = game:GetService("UserInputService")
local Event = RS.Control.RemoteEvent

local function keyDown(key)
	return UIS:IsKeyDown(key)
end

local function Input (input,processed)
	if processed then return end

	if input.UserInputType == Enum.UserInputType.Keyboard then
		Event:FireServer(keyDown(Enum.KeyCode.W),keyDown(Enum.KeyCode.A),keyDown(Enum.KeyCode.S),keyDown(Enum.KeyCode.D))
	end
	end

UIS.InputBegan:Connect(Input)
UIS.InputEnded:Connect(Input)
--//Server Side
Event.OnServerEvent:Connect(function(plr,w,a,s,d)
		Velocity.W.Value = w
		Velocity.A.Value = a
		Velocity.S.Value = s
		Velocity.D.Value = d
end)

Any help is appreciated. Thanks

1 Like

why do you even need this and for what

well for starters if your’e only moving your player, and not moving another player though server then all this can be client. idk if I worded that right, but basically all players have the same client script so if you’re not moving other players though the local players actions then make it all local since it’s a moving script.

Second for your uis just call the function like this

local keys = {
w = Velocity.W.Value;
A = Velocity.W.Value;
}

uis.InputBegan:Connect(function(key, gpe)
if gpe then return end
if key.KeyCode == Enum.KeyCode.A then
--code
print(keys.w)
end
end)

There’s many ways to make this better but just keep it local and dont overcomplicate functions. Roblox has these specific function in place for a reason no reason to do local function in this scenario.

1 Like

You’re going to want to actually set the network owner to the client and have it replicated that way. Setting network ownership will allow the client to move it and just send updates to the server. The reason it feels laggy is you are waiting potentially a long time for the button presses to get to the server and information to come back before any changes are seen.

1 Like

I guess I needed to elaborate. Basically it’s that one epic minigames game and you move the ball. I want to control the ball using the keys pressed so yea.

I would love to do that. How do I put network ownership to use??

This explains it pretty well imo.

1 Like

Example 3 mathces pretty well with my case. THanks

A new problem is now occurring - the collision script is horribly broken. The script basically renders collision and makes the balls bounce off. Now with the network ownership in use, it knocks you back back-and-forth until you fling away uncontrollably.

How do I fix this??