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)
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