How can you get the distance from player's mouse to a part?

I just want to know how to get the minimum distance from the player’s mouse to a part.

I have thought of doing (mouse.Hit.Position - game.Workspace.Part.Position).Magnitude, but that part.position would give me the center of the part which is not really the minimum distance.

You can just add/subtract the parts size from its position so it’s not in the center and get it however you want.

2 Likes

How can I do that?
30000000000

Raycast from the mouse position to part, and get the distance from there.

local ray = Ray.new(Mouse.Hit.p, part.Position - Mouse.Hit.p)
local part, position = workspace:FindPartsInRegion3WithWhiteList(ray, {part})
local magnitude = (Mouse.Hit.p - position).Magnitude

This won’t be 100% accurate, but it’s much closer than grabbing the part’s central position

2 Likes

I got an error

Unable to cast Ray to Region3

But I like your idea of doing this

wait what? didn’t see your post in time. 30000

Mayor just made a typo, it’s supposed to be

local ray = Ray.new(Mouse.Hit.p, part.Position - Mouse.Hit.p)
local part, position = workspace:FindPartOnRayWithWhitelist(ray, {part})
local magnitude = (Mouse.Hit.p - position).Magnitude
2 Likes

For some reason when I print the magnitude, the value doesn’t change and it doesn’t make sense to me.
I get prints like 3000 and 2000. I am using a local script btw.

Could you please review my code?

local mouse = game.Players.LocalPlayer:GetMouse()
local part = game.Workspace.WaterPlate

local ray = Ray.new(mouse.Hit.Position, part.Position - mouse.Hit.Position)
local part, position = game.Workspace:FindPartOnRayWithWhitelist(ray, {part})
local magnitude = (mouse.Hit.Position - position).Magnitude


while true do
	print(magnitude)
	wait(1)
end

That’s because you’re only checking the distance once, then printing that same distance every second. Try this

local mouse = game.Players.LocalPlayer:GetMouse()
local part = game.Workspace.WaterPlate

while true do
	local ray = Ray.new(mouse.Hit.Position, part.Position - mouse.Hit.Position)
	local part, position = game.Workspace:FindPartOnRayWithWhitelist(ray, {part})
	local magnitude = (mouse.Hit.Position - position).Magnitude
	print(magnitude)
	wait(1)
end