Help with moving part on Mouse Move

Hello, I have been trying to make a part move when my mouse is moving, I am able to do that but I can’t figure out how would I make it stick to the terrain and not go up in the air and is sticking onto the player camera

This is what is happening currently:
https://gyazo.com/9dee3ee6ef398aeed4b82c2a173883f2

I wrote a simple script for this:

local p2 = game.ReplicatedStorage.ItemsCraft[script.Parent.Parent.Name]:Clone()

p2.Parent = game.Workspace

local m = game.Players.LocalPlayer:GetMouse();

m.Move:Connect(function()
	function mouseHit(distance)
		local ray = Ray.new(m.UnitRay.Origin, m.UnitRay.Direction * distance)
		local _, position = workspace:FindPartOnRay(ray)
		
		return position					
    	end  		
	
		
   p2.Position = mouseHit(50)
end)
1 Like

It looks like when you’re using :FindPartOnRay(), the ray is hitting the object you’re moving around. To fix this, there’s a second argument you can add as an “ignore descendants” object, where the ray ignores the object and all of its descendants. If this is indeed the error, then adding p2 as this second argument should fix your problem because the ray would ignore p2 and its descendants:

local _, position = workspace:FindPartOnRay(ray,p2) 

This should be enough to fix your code for the time being. Alternatively, if you have multiple objects you want the ray to ignore, you can create a folder for these objects in workspace and place all objects to ignore inside of that folder, then pass the folder as an argument:

--in some server script (or done beforehand in studio) 
local folder = Instance.new("Folder",workspace) 
folder.Name = "RayIgnoreFolder" 

--outside of function after p2 is created 
p2.Parent = folder 

--inside of the function in place of the current :FindPartOnRay() line 
local _, position = workspace:FindPartOnRay(ray,folder) 

If this still isn’t specific enough for your game or somehow gets in the way, there are other alternatives to :FindPartOnRay() which can be found here under functions, but for this specific problem, you probably won’t need them. I’ll still link to them for future reference -

4 Likes

I advise you to use renderstepped, because as seen in the video, the “ball” doesn’t budge when you scroll out.

Mouse.TargetFilter = p2 -- This insures that it won't lag

game:GetService("Runservice").RenderStepped:Connect(function()
    if Mouse.Target = workspace.Terrain then -- detects if the target is terrain
        p2.Position = CFrame.new(Mouse.Hit.p.X, Mouse.Hit.p.Y, Mouse.Hit.p.Z)
    end
end)
5 Likes

Thanks to both of you for helping me out with the problem! :grinning: