How to drag a part using mouse and BodyPosition

I’ve been trying to make a dragging system for certain parts because I’m creating a portal spinoff but it doesn’t seem to be working all the time. This is the script I have currently and I cant find any errors or problems with it.

local uis = game:GetService(“UserInputService”)
local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local obj = nil
local stop = false

uis.InputBegan:Connect(function(key)
if key.UserInputType == Enum.UserInputType.MouseButton2 then
if mouse.Target and mouse.Target.Anchored == false and mouse.Target.Parent == workspace then
obj = mouse.Target
local force = Instance.new(“BodyPosition”, obj)
force.Name = “Force”
force.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
stop = true
repeat
force.Position = (workspace.CurrentCamera.CFrame + workspace.CurrentCamera.CFrame.LookVector * 10).p
wait()
until stop == false
end
end
end)

uis.InputEnded:Connect(function(key)
if key.UserInputType == Enum.UserInputType.MouseButton2 and obj ~= nil then
obj.Force:Destroy()
stop = false
obj = nil
end
end)

You need to set the Network owner of the parts to the player that’s dragging them on the server

1 Like

explain further please. I don’t quite understand.

Network ownership basically gives a player full control of a part that is replicated to the server.

You need a way to identify on the server when a player is going to drag the part. This can be done with remote events. Whenever that is handled, the server can give network ownership to the player dragging the part.

part:SetNetworkOwner(PLAYER)

Pass the part as the object to be dragged and PLAYER as the player to be given network ownership to. Be sure to put this in a server script.

2 Likes

So instead of using a local script which would be a lot easier I should use remoteevents?

No, both a localscript and remote event are both minimum requirements if there are no server events declaring when set network owner needs to take place (described in next section). Your localscript needs to fire the remote event telling the server that a player wants to drag the part. Although this contains a major security risk, you can easily fix it by adding server-sided checks.

If there are already events on the server declaring a player is moving a brick, a remote event isn’t necessary. If that’s the case, then just set the network owner of the part to the player. If you don’t know what any of this means, try checking out some YouTube tutorials explaining remote events.

If you can, elaborate or provide a video showing what you mean by

I’m back from taking a small break and tried your solution and it worked thanks!