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)