Raycast and MousePosition is innacurate and does not select part correctly

  1. What do you want to achieve? The part should be selected/clicked properly

  2. What is the issue? Parts are hard to select, some refuse to select at all.

  3. What solutions have you tried so far? I’ve tried adding an offset and have looked on the dev forum but have not found anything which is useful.

I’m trying to make a system which adds a highlight part to a part that it is in a folder if it has been hovered over. If the user clicks on it, the part becomes selected.

However, it seems to be innacurate, check the video attached.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local currentlySelected = player.PlayerGui:WaitForChild("Main").CurrentlySelected

local selectedPart = nil
local hoverHighlight = nil

local formerSelectedPart = nil

local function createHighlight(part, isFilled)
	local highlight = Instance.new("Highlight")
	highlight.Parent = part
	highlight.FillColor = workspace[player.Name]["Values"]["PlayerColor"].Value.Color
	if isFilled == true then
		highlight.FillTransparency = 0.5
	else
		highlight.FillTransparency = 1
	end
	return highlight
end

mouse.Button1Down:Connect(function()
	if currentlySelected ~= "Add" then
		local mousePosition = mouse.Hit.p
		local part = workspace:FindPartOnRayWithWhitelist(
			Ray.new(mousePosition, Vector3.new(0, -1, 0)),
			{workspace[player.Name]["Parts"]}
		)

		if part and part:IsA("Part") then
			if hoverHighlight then
				hoverHighlight:Destroy()
				hoverHighlight = nil
			end

			if formerSelectedPart then
				formerSelectedPart.Highlight:Destroy()
			end

			selectedPart = part
			formerSelectedPart = selectedPart
			createHighlight(selectedPart, true)
		end
	end
end)

mouse.Move:Connect(function()
	if currentlySelected ~= "Add" then
		local mousePosition = mouse.Hit.p
		local part = workspace:FindPartOnRayWithWhitelist(
			Ray.new(mousePosition, Vector3.new(0, -1, 0)),
			{workspace[player.Name]["Parts"]}
		)

		if part and part:IsA("Part") and part ~= selectedPart then
			if hoverHighlight then
				hoverHighlight:Destroy()
			end

			hoverHighlight = createHighlight(part, false)
		elseif not part and hoverHighlight then
			hoverHighlight:Destroy()
			hoverHighlight = nil
		end
	end
end)

You don’t need to use raycasts. I have made a similar system before and using mouse.Target worked perfectly for me.

Its because your ray isn’t translated to the screen point correctly.

Here is a function that will give you a ray.

local SELECTION_DISTANCE = 10
local function getMouseRay(): Ray
	local mousePosition = UserInputService:GetMouseLocation()
	local unitRay = Camera:ScreenPointToRay(mousePosition.X, mousePosition.Y)
	return Ray.new(unitRay.Origin, unitRay.Direction * SELECTION_DISTANCE)
end

can’t set raycastparams with mouse.target

I meant without using raycasts at all

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