Make part follow mouse

I am trying to make a part follow the player’s mouse so that I can attach later a light to it and make a flashlight that follows the mouse.

The issue is that the part is instable and keeps moving which makes it difficult to work with

So far I’ve tried:

--// variables
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local player = Players.LocalPlayer

local part = Instance.new("Part")
part.Parent = workspace

local mouse = player:GetMouse()

--// function
RunService.RenderStepped:Connect(function()
	part.CFrame = mouse.Hit
end)

You can use UserInputService and raycasting to achieve this

local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true

local raycastparams = RaycastParams.new()
raycastparams.FilterType = Enum.RaycastFilterType.Blacklist
raycastparams.FilterDescendantsInstances = {part}

game:GetService("UserInputService").InputChanged:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseMovement then
		local ray = game.workspace.CurrentCamera:ScreenPointToRay(input.Position.X, input.Position.Y)
		local result = workspace:Raycast(ray.Origin, ray.Direction * 500, raycastparams)
		if result ~= nil then
			part.Position = result.Position
		end
	end
end)
1 Like

You need to blacklist the part from the mouse’s potential targets.
mouse.TargetFilter = part

Inside the renderstepped function, paste this

RunService.RenderStepped:Connect(function()
     mouse.TargetFilter = part --The mouse will avoid hitting the part
     part.Position = mouse.Hit.Position --the parts position is equal to the position that the mouse hits
    
end
1 Like