How would I get the mouse pos in a server script?

Im trying to make a gun but cant find a way to get the mouse position any help?

script.Parent.Main.Shoot.OnServerEvent:Connect(function()
	local bullet = Instance.new("Part")
	bullet.Shape = "Ball"
	bullet.Size = Vector3.new(0.4,0.4,0.4)
	bullet.Parent = game.Workspace
	bullet.CFrame = Mouse.Hit -- here
	bullet.Anchored = true
	function hits(s)
		if s.Parent:FindFirstChild("Humanoid") then
			s.Parent.Humanoid.Health = 0
			bullet:remove()
		end
	end
	bullet.Touched:connect(hits)
end)

5 Likes

The mouse object is not replicated (or accessible) to the server, because the mouse is for client input.

That said, you could use a remote event to send the player’s current mouse position to the server for processing. In your case, you could add a parameter to your OnServerEvent connection.

And on the client:

--//Send mouse position in game world
shootRemote:FireServer(mouse.Hit.Position)
7 Likes

How would I add that to the script?

First step, change that to:
function(player, mousePos)
So first line should be:
script.Parent.Main.Shoot.OnServerEvent:Connect(function(player, mousePos)

Now in the local script you will need 4 things

  1. The Player local player = game:GetService("Players")
  2. The mouse local mouse = player:GetMouse()
  3. The Remote Event (Wherever thats located)
  4. Fire The Remote Event RemoteEvent:FireServer(mouse.Hit.Position)
3 Likes

So how would I incorporate that into bullet.CFrame = Mouse.Hit?

bullet.Position = mousePos

Try something like that.

error
Screen Shot 2022-05-20 at 7.19.00 PM

I edited my reply to use Position

you could also just have the server fire a remotefunction to the client and have it return the mouse coordinates

True, however invoking the client from server and then having the client return it’s mouse data is double the communication between client and server. Therefore doubling the latency.