Need help stopping a part going through the ground

Hello, I wrote a small object moving system for my game, when I use it though parts go into the ground and go into other parts, how could I and what are some ways I could fix this?

Btw these pictures of me using the system and having the thing happen:
Screenshot_58
Screenshot_59

Here is my script for further context:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local mtarget
local down

function clickObj()
	if mouse.Target ~= nil and mouse.Target:IsDescendantOf(game.Workspace.Objects) then
		mtarget = mouse.Target
		print(mtarget)
		mouse.TargetFilter = mtarget
		print(mouse.TargetFilter)
		down = true
	end
end

mouse.Button1Down:Connect(clickObj)

function mouseMove()
	if down and mtarget then
		local posX,posY,posZ = mouse.Hit.X, mouse.Hit.Y, mouse.Hit.Z
		
		mtarget.Position = Vector3.new(posX,posY,posZ)
	end
end

mouse.Move:Connect(mouseMove)

function mouseDown()
	down = false
	mtarget = nil
	mouse.TargetFilter = nil
end

mouse.Button1Up:Connect(mouseDown)
1 Like

I don’t get the question right , do you mean collision?

I suppose so yes, the part is CanCollide but it still moves through the ground and other parts.

To avoid the part going through the ground you need to increase the Y Position of it with half the Y Size. Should be the same thing with all other directions too.

I tried that but it errors and says that it expected a vector3 but got a number, I have tried to do a vector3.new but it gives me the same error.

The Position property is a vector3 and therefore you need to set the entire vector3 every time you want to change that property.

Try replacing that with:

mtarget.Position = Vector3.new(posX,posY + (mtarget.Size.Y/2),posZ)

And it should stop the part from going through the ground.

1 Like

As you said that, I was typing it xd

It works, how would I make it so that depending on what face the mouse is hitting, it changes that part of the position?

I’m on phone so I can’t test anything for you but you should be able to use Mouse.TargetSurface to figure out which side you are hovering on.

Okay, thank you, I will let you know if it works.