How do I check if my mouse is on a player?

Hey so Im currently working on a script that checks if my mouse position is on a player or on a player model but im a bit stuck. Can anyone help?

You can use mouse.Target like so:

local runService = game:GetService("RunService")

local player = game.Players.LocalPlayer

local mouse = player:GetMouse()

runService.Heartbeat:Connect(function() -- or whatever event
	if game.Players:GetPlayerFromCharacter(mouse.Target) then
		print(mouse.Target)
	end
end)

This wouldn’t quite work cus mouse.Target returns a BasePart, and a Character is a Model. Instead, you should change it to be this:

if mouse.Target then
    local Character = mouse.Target.Parent
    if not Character:FindFirstChild("Humanoid") then return end
    print(Character)
end

You can then get the Player if you want by calling that GetPlayerFromCharacter() function

You’re right, thank you for correcting me

1 Like

I believe it’d be more useful for @BlackPantherGamer101 to use Instance:FindFirstAncestorOfClass(className) in this scenario due to possibility of the existence of accessory parts.

local function getPlayerFromMouseTarget(): Player?
	if mouse.Target then
		local character = mouse.Target:FindFirstAncestorOfClass("Model")
		if character and character:FindFirstChild("Humanoid") then
			return game.Players:GetPlayerFromCharacter(character)
		end
	end
	
	return
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.