How to detect UserInputService when mouse hover on a part

So basically, i used clickDetector on a part to detect mouse hover and change the cursor image. How can I detect if the player press E when they hover their mouse on the part. By the way, how can I detect the same thing on a tool?

You can use “Mouse.Target” to return the object the mouse is hovering on.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

-- We must get the UserInputService before we can use it
local UserInputService = game:GetService("UserInputService")

-- A sample function providing one usage of InputBegan
local function onInputBegan(input, gameProcessed)
	if gameProcessed then return end
	
	if input.UserInputType == Enum.UserInputType.Keyboard and input.KeyCode == Enum.KeyCode.E then
		print("The E button has been pressed! The target was " .. mouse.Target)
	end
end
UserInputService.InputBegan:Connect(onInputBegan)
1 Like

Well, your solution worked, but how can I set a max activation distance for this? Thanks in advance!

Simply check the distance between the player’s character and the part.

local part = workspace.Part --The part that needs to be hovered over
local maxDist = 30 --Max distance

local dist = (player.Character.PrimaryPart.Position - part.Position).Magnitude

if dist <= maxDist then
    --They are within max distance
end
2 Likes

If you have access to the player as a variable, you can use Player:DistanceFromCharacter(part.Position) instead of .Magnitude which is faster because it is a built-in function which utilizes C++ and requires less indexing.

3 Likes

Bare in mind you’ll need to check if the distance is > 0 as the method returns 0 if the player has no character.

3 Likes