Model floating when following the player mouse

when i make a script that makes a part follow the player mouse the part is floating how can i make it snap to the ground ? or to the nearest floor

local mouse = game.Players.LocalPlayer:GetMouse()

local event = mouse.Move:Connect(function()

	Part.Position = Vector3.new(mouse.Hit.X, Part.Position.Y, mouse.Hit.Z)
				
end)
1 Like

You’ll need to add the normal multiplied by half of the instance size that got hit by the mouse raycast to the position. You can do this by making a raycast using mouse.UnitRay. then you use the normal of the raycastResult which you will get from doing workspace:Raycast(unitray.origin, unitray/direction * max_raycast_distance, ray_params) Here’s some code I wrote inside of a function. It has a “selection” variable, which just stores the current model or part that is supposed to move by the mouse.

local selection: (Model|BasePart)? = nil

local camera = workspace.CurrentCamera

local function update_selection_poisition()
       if selection == nil then return end
	local new_position: Vector3? = nil
	local unit_ray: Ray = camera.UnitRay
	local raycast_result = workspace:Raycast(unit_ray.Origin, unit_ray.Direction * 1000)
	if raycast_result then
		local hit: Vector3 = raycast_result.Position
		local normal: Vector3 = raycast_result.Normal
		local Box: Vector3 = if selection:IsA("Model") then selection:GetExtentsSize() else (selection :: BasePart).Size
			new_position = Vector3.new(hit.X + normal.X * Box.X / 2, hit.Y + normal.Y * Box.Y / 2, hit.Z + normal.Z * Box.Z / 2)
	else
		new_position = unit_ray.Origin + unit_ray.Direction * selection_forward_offset
	end

        -- Update position of selection
	local pivot: CFrame = (selection :: Model | BasePart):GetPivot();
	(selection :: Model | BasePart):PivotTo(CFrame.new(new_position :: Vector3) * (pivot - pivot.Position));
end

game:GetService("RunService").RenderStepped:Connect(function()
   update_selection_position()
end)

In your case selection will just be the Part, so assign it to that I guess, and you call the update_selection_position function from the mouse.Move function. Hope that helps!

1 Like