Raycast with Mouse not working

Hello everyone!

I recently have been trying to learn raycasting more and decided to try to make something where it raycasts from your mouse to the hit if you click somewhere. It works, but it offsets the mouse position a bit, no matter the normal / surface direction.

Code
local uis = game:GetService("UserInputService")

local player = game.Players.LocalPlayer

local camera = workspace.CurrentCamera

local length = 500

local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {game.Workspace.Baseplate}

uis.InputBegan:Connect(function(input, gpe)
	if gpe then return end
	
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		local mousePos = uis:GetMouseLocation()
		local unitRay = camera:ScreenPointToRay(mousePos.X, mousePos.Y)
		
		local rayResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * length, params)
		
		if rayResult then
			local newPart = game.ReplicatedStorage.Part:Clone()
			newPart.Parent = game.Workspace
			
			newPart.CFrame = CFrame.lookAt(rayResult.Position, rayResult.Position + rayResult.Normal)
			
			table.insert(params.FilterDescendantsInstances, newPart)
			
			print(#params.FilterDescendantsInstances)
			
			game:GetService("Debris"):AddItem(newPart, 3)
		end
	end
end)
Result (No Output Errors)

image
image
image
image

The target/goal result would be that the part is at the tip of the mouse and on the part.

I am really boggled as to why this offset is happening, but I would appreciate it if anyone could provide an answer.

2 Likes

This is happening because of the gui inset, where the topbar used to be. This is mentioned on the API page. If you want to account for this, you can simply subtract the gui inset from the mouse position. To get the gui inset, use game:GetService("GuiService"):GetGuiInset()

3 Likes