How to fix weird bug when trying to make a PART follow the mouse

Hello, I am making a grab system but I have a weird bug

when I set the NewPart to follow the Mouse in the runservice, the part goes back and forth towards the players camera

I tried NewPart.Position = Mouse.Hit.Position * 2 but that makes the part far away and keeps clipping out of the world

heres a vidoe :

robloxapp-20220127-0326029.wmv (856.9 KB)

local ReplicatedS = game:GetService("ReplicatedStorage")
local Player = game:GetService("Players").LocalPlayer

local Mouse = Player:GetMouse()

local GrabRemote = ReplicatedS.Remotes:WaitForChild("GrabRemote")

local CanGrab




local function GrabObject()
	
	local Target = Mouse.Target
	
	if Target and Target.Anchored == false then
		
		local NewPart = Instance.new("Part")
		--NewPart.Size = Vector3.new(0.5,0.5,0.5)
		NewPart.Shape = Enum.PartType.Ball
		NewPart.Parent = workspace
		
		CanGrab = RunService.RenderStepped:Connect(function()

			NewPart.Position = Mouse.Hit.Position
		
		end)
	end
	
end




local function ReleaseObject()
	
end




Mouse.Button1Down:Connect(GrabObject)
Mouse.Button1Up:Connect(ReleaseObject)```

if you need to, you can test the code and see the problem for yourself,

just add a localscript in startercharacterscripts and paste the code,

then make a part in workspace and make sure its unanchored

then click on that part

You aren’t filtering the part you are holding from the Mouse object, to do that you could use TargetFilter

local ReplicatedS = game:GetService("ReplicatedStorage")
local Player = game:GetService("Players").LocalPlayer

local Mouse = Player:GetMouse()

local GrabRemote = ReplicatedS.Remotes:WaitForChild("GrabRemote")

local CanGrab




local function GrabObject()
	
	local Target = Mouse.Target
	
	if Target and Target.Anchored == false then
		
		local NewPart = Instance.new("Part")
		--NewPart.Size = Vector3.new(0.5,0.5,0.5)
		NewPart.Shape = Enum.PartType.Ball
		NewPart.Parent = workspace
		Mouse.TargetFilter = NewPart
		
		CanGrab = RunService.RenderStepped:Connect(function()

			NewPart.Position = Mouse.Hit.Position
		
		end)
	end
	
end




local function ReleaseObject()
	
end




Mouse.Button1Down:Connect(GrabObject)
Mouse.Button1Up:Connect(ReleaseObject)

why do i need to filter the part?

Because the Mouse.Hit property counts that part too, resulting in it repeatedly moving it closer and closer until it’s too close to be seen by Mouse.Hit (after that, it’ll return the part to where you’d expect it to be & start moving it closer again)

ahh, so do I change the Target Variable to local Target = Mouse.TargetFilter?

what else do i have to do?

No, the target filter is the filter itself, you have to put the part in the filter so it isn’t seen by the Mouse

Mouse.TargetFilter = NewPart
2 Likes

ohhh ok, it works now, thanks.