Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

My mouse.Hit.p is inaccurate? How do I make the aim more precise or did I mess something up?

When clicking, my script in a tool uses Target to make sure it is on a part. When it knows it's clicking a part, it goes on to use mouse.Hit.p to create a ray. The ray then makes sure that the part it hits is named after what I want it to be named, and then it fires an event. But, for some odd reason I cant wrap my head around I have to hold my mouse slightly above the part not on it, any explanation as to why or some other methods I could use that function easier or something?

Clip of the problem : https://gyazo.com/054208b4f6f8593b6ced986dfc15f920

The script in the tool:

local Players = game:GetService("Players")
local localPlayer = game.Players.LocalPlayer 
local PartTransRequest = game.ReplicatedStorage:WaitForChild("PartTransRequest") -- event for making part transparent


-- grab the mouse
local mouse = localPlayer:GetMouse() -- get mouse
local target = mouse.Target -- get mouse target to check if its clicking a part


Equipped = false -- so the code doesnt repeat when its not equipped

script.Parent.Equipped:connect(function()
	Equipped = true
end)

script.Parent.Unequipped:Connect(function()
	Equipped = false
end)

mouse.Button1Down:connect(function()

	local head = localPlayer.Character:FindFirstChild("Head")
	local rayOrigin = script.Parent.Handle.Position
	local lookDirection = mouse.Hit.p 
	
	
	print"test 1" 
	
	if Equipped == true then
		
		print"test 2"
		if target ~= nil then -- if the part is there create a ray
			local ray = Ray.new(rayOrigin, lookDirection)
			
			
			local hitPart, hitPosition = workspace:FindPartOnRay(ray)
			
			
			print"test 3"
			if hitPart then
				print"test 4"
				if hitPart.Name == "BOBJECT" then do -- if its name is BOBJECT then itll do the event
						game.ReplicatedStorage.PartTransRequest:FireServer(hitPart)
				end		
				end
				end
				
	end
	end
end)
	
	

1 answer

when you use Ray.new, the second argument is an offset from the origin

to convert a position in world space to position's local space (which in this case is the origin's), you can just do b - a

local lookDirection = mouse.Hit.p - rayOrigin

also, you should consider changing to the new raycasting api, since FindPartOnRay is deprecated

the documentation for it is here https://developer.roblox.com/en-us/api-reference/function/WorldRoot/Raycast

This discussion is preserved as it was. New answers, comments, and votes are closed.