How to detect if a players mouse is on a part

What I’m trying to do is figure out how to detect when a player is touching a part with their mouse. So for example if a player was to put their mouse on the part it would change color, and if they stopped touching it the part would change back to the original color.

4 Likes

Use mouse.Hit and detect if it is that part

Try using mouse.Hit, like as @SnarlyZoo mentioned, but don’t forget to put it inside of some while loop.

I’m confused on what you mean by that.

Try reading this article about player’s mouse.

The Target property of the mouse indicates what part the Mouse is on. Here’s a script for what you’re trying to achieve:

local rs = game:GetService("RunService")
local last, originalColour

rs.RenderStepped:Connect(function()
    local targ = mouse.Target

    if not last or targ ~= last then
        if last then
            last.Color = originalColour
        end

        originalColor = targ.Color
        targ.Color = Color3.new(0, 0, 1)
    elseif last and targ ~= nil then
        last.Color = originalColor
        last = nil
        originalColor = nil
    end
end)
5 Likes

So would this be going into a local script inside the part?

No, it would most likely be in StarterPlayerScripts in a LocalScript, if you just want to change it clientside. You would define mouse as game.Players.LocalPlayer:GetMouse().

What line is detecting what’s the correct part that should react if touched?

There are actually two functions made for this!

They are called MouseHoverEnter and MouseHoverLeave. These are used with ClickDetectors. You can assign these functions to activate when a player’s mouse enters / leaves a part on screen.

Here is an example of a script!

local part = script.Parent
local cd = part.ClickDetector

local MouseOver = function()
    script.Parent.BrickColor = BrickColor.new("Really red")
end

local MouseOut = function()
    script.Parent.BrickColor = BrickColor.new("Medium stone grey")
end

cd.MouseHoverEnter:Connect(MouseOver)
cd.MouseHoverLeave:Connect(MouseOut)

This is obviously the most basic you can get. The interesting thing about this is that no matter the size or shape on your screen, it will always work and not have funky hitboxes. I hope you find this information useful!

13 Likes

Yes! Thank you this helps me a lot.

2 Likes