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