Getting mouse position without firing remotes?

Hi. I’m working on a move-system and I need to update the mouse position very frequently. I’m aware that firing remotes a lot is lag intensive, but I am also unable to do anything about this due to the fact that Player:GetMouse() is clientsided only. Is there a way for me to get the mouse position on the server without firing remotes every 0.1 second?

Hello

There is no way to get a client’s mouse from the server-side. If you need the server to know the location of a client’s mouse then you need to send the location via RemoteEvents, there is
no way around that.
However, you can reduce the speed at whichthe Events are fired.
Instead of firing them everytime the mouse changes it’s position or every .1 seconds
you can change it when you click a mousebutton or something else.

Example:

--[[
      LocalScript
]]
Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")
Mouse = game.Players.LocalPlayer:GetMouse()

-- Position variable
MousePosition = {0, 0}

-- fires event once when the left mouse button is down
Mouse.Button1Down:Connect(function()
  Event:FireServer(MousePosition)
end)

--  updates the MousePosition variable everytime the position of the mouse changes
Mouse.Move:Connect(function()
  MousePosition = {Mouse.X, Mouse.Y}
end)

--[[
      ServerScript
]]
game.ReplicatedStorage:WaitForChild("RemoteEvent").OnServerEvent:Connect(function(client, mposition)
  print(client.Name.."'s mouse is at  X: "..table.concat(mposition, " / Y: "))
end)

I hope that this can help you out.

Thank you for the answer. If I use Mouse.Move to fire the remote, at what rate will it fire? How fast and how many times in a second

As soon as the position of the mouse has been changed. Depending on your framerate and how much you move your mouse it could fire the event up to 60 times a second.

Would this mean that using Mouse.Move is more lag intensive than a while loop that fires every 0.1 second?

When you use it to fire events, surely is. However unlike the while-loop. the .Move would only fire when the mouse is moving. Thus when it’s not, no event would be fired.

Not exactly because your loop will keep running even when the player doesn’t move the mouse

You could use a mixture of the mouse’s Move event/signal and a debounce in order to limit the total number of times the server is fired.

local Game = game
local Players = Game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

local Time = os.time()

local function OnMouseMove()
	if os.time() - Time < 1 then return end --Ignore if the event was fired in the last 1 seconds.
	Time = os.time()
	--Fire the server here.
end

Mouse.Move:Connect(OnMouseMove)
1 Like

This was so clever! Thank you, however os.time returns whole numbers only, so I replaced it with tick()

I meant for the script to have a debounce of 1 second not 0.1 seconds, thanks for catching that.