Raycast mouse script lagging heavily

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to fix my mouse position finding script

  2. What is the issue? Include screenshots / videos if possible!
    The script lags the game a lot when the target is nil and spams errors, It seems to still do stuff when the mouse isnt moving but only seems to break when the target is the sky then it will create errors until I close the server

  3. What solutions have you tried so far? Did you look for solutions on the Creator Hub?
    I tried a system where the mouse only updates if it is moved and every half a second

--local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local target = Instance.new("Part")
local UserInputService = game:GetService("UserInputService")
target.Parent = game.Workspace
target.CanQuery = false
target.CanCollide = false
target.Transparency = 0.6
target.Size = Vector3.new(1,1,1)
target.Anchored = true
local event = game.ReplicatedStorage.TargetPosition

local Time = os.time()

local function OnMouseMove(pos)
	if os.time() - Time < 1 then return end --Ignore if the event was fired in the last 1 seconds.
	Time = os.time()
	event:FireServer(pos)-- *
end

game:GetService("RunService").Heartbeat:Connect(function()
	if not game:IsLoaded() then return end
	local mousePosition = UserInputService:GetMouseLocation()
	local ray = workspace.CurrentCamera:ViewportPointToRay(mousePosition.X, mousePosition.Y)
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.FilterDescendantsInstances = player.Character:GetDescendants()
	local result = workspace:Raycast(ray.Origin, ray.Direction * 200, raycastParams)
	mouse.Move:Connect(function()
		if result.Position ~= nil then
			OnMouseMove(result.Position)
		end
	end)
end)

*(By the way the server script just prints the output at this line and nothing else)

  1. Take your raycast params and the mouse.move event out of the runservice loop.
  2. Instead of player.Character:GetDescendants() just do {player.Character}.
  3. instead of UserInputService:GetMouseLocation() just use mouse.X, mouse.Y.

Also if youre only looking to fire the event every 1 seconds, why not just move everything from a runService loop to a while task.wait(1) loop

Mouse already has .Target and .Hit property
I dont see point in what you are doing

what the hell is this

a new connection every frame that fires a remote event every frame
this is horrific

WHY are you even using :GetMouseLocation, you can just do mouse.Hit.Position

i am so confused

most likely for raycast params so they can filter out the character

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