Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I get the Vector2 distance from the mouse to a part?

Asked by 1 year ago

the title explains it lol

1 answer

Log in to vote
1
Answered by
imKirda 4491 Moderation Voter Community Moderator
1 year ago

You can use :WorldToScreenPoint to get Vector2 position from Vector3, then you get the distance between that and :GetMouseLocation, this is your result.

-- StarterPlayerScripts.LocalScript
local UserInputService = game:GetService("UserInputService")
local Workspace = game:GetService("Workspace")

local part = Workspace:WaitForChild("Part")

while task.wait(0.1) do
    local mouse_location = UserInputService:GetMouseLocation()
    local part_location = Workspace.CurrentCamera:WorldToViewportPoint(part.Position)

    local distance = (mouse_location - Vector2.new(part_location.X, part_location.Y)).Magnitude

    print(distance)
end

When you write (A - B).Magnitude, you get the distance between A and B, however, in this case there is a small issue that mouse_location is Vector2 and part_location is Vector3, Vector2.new(part_location.X, part_location.Y) converts the Vector3 to Vector2, because otherwise we couldn't write A - B (Can't subtract Vector2 with Vector3).

Here is an example code that makes the part more red the closer you move your cursor towards it:

-- StarterPlayerScripts.LocalScript
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

local part = Workspace:WaitForChild("Part")

RunService.Heartbeat:Connect(function()
    local mouse_location = UserInputService:GetMouseLocation()
    local part_location = Workspace.CurrentCamera:WorldToViewportPoint(part.Position)

    local distance = (mouse_location - Vector2.new(part_location.X, part_location.Y)).Magnitude

    part.Color = Color3.new(1 - math.min(100, distance) / 100, 0, 0)
end)

Ad

Answer this question