MeshPart Moves Into Camera When Mouse is Idle

I made this script that makes when a textbutton is pressed it takesout a meshpart from replicated storage and makes it follow players mouse untul i click on the screen to anchor the meshpart but teres a glitch that makest he meshpart go towards the camera

the localscript

-- Your script here
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local button = script.Parent
local partToPlace
local lastPosition
local camera = workspace.CurrentCamera

button.MouseButton1Click:Connect(function()
	if partToPlace then
		partToPlace:Destroy()
	end

	local part = ReplicatedStorage:FindFirstChild("MeshPart")
	if part then
		partToPlace = part:Clone()
		partToPlace.Parent = workspace
		partToPlace.Transparency = 0.5
		partToPlace.CanCollide = false
		partToPlace.Anchored = true
	else
		warn("MeshPart not found in ReplicatedStorage!")
		return
	end

	local updateConnection
	updateConnection = RunService.RenderStepped:Connect(function()
		if partToPlace then
			local mouseLocation = UserInputService:GetMouseLocation()
			local ray = camera:ScreenPointToRay(mouseLocation.X, mouseLocation.Y)
			local raycastParams = RaycastParams.new()
			raycastParams.FilterDescendantsInstances = {workspace.CurrentCamera}
			raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

			local result = workspace:Raycast(ray.Origin, ray.Direction * 1000, raycastParams)
			local positionToSet

			if result then
				positionToSet = Vector3.new(result.Position.X, result.Position.Y + partToPlace.Size.Y / 2, result.Position.Z)
			elseif lastPosition then
				positionToSet = lastPosition
			else
				positionToSet = ray.Origin + ray.Direction * 10
			end

			partToPlace.Position = positionToSet
			lastPosition = positionToSet
		end
	end)

	UserInputService.InputBegan:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			if partToPlace then
				partToPlace.Transparency = 0
				partToPlace.CanCollide = true
				partToPlace.Anchored = true
				partToPlace = nil
				updateConnection:Disconnect()
			else
				warn("partToPlace is nil when trying to finalize placement!")
			end
		end
	end)
end)

Make the MeshPart not have collision until it is placed.

You need to blacklist the meshpart from the raycast, otherwise there’s a feedback loop where the raycast hits the meshpart which then moves closer because the surface of the mesh is closer to the camera.

Blacklisting CurrentCamera doesn’t do anything because it’s not a basepart.

Both mine and @NOVEIGMA’s solutions should work.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.