Need help with remote events and server scripts

Recently I made a dragging system, and I am really happy how it works, but I had run in an issue when I tested that same system with multiple people.

For context, when player presses his left mouse button, 2 remote events fire. First event creates an attachment, alignPosition and alignOrientation constraint, positions the attachment at the mouse.Hit position and parents it to a mouse target, and connects te constraints to the attachment. 2nd event is not fired just once, but every frame, and what it practically does, is updates the Position for alignPosition constraint.

When players stops pressing the left mouse button, the attachment and constraints are deleted, and the 2nd event is also stopped from firing.

Here is how it looks on server script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local holdPoint
local alignPosition
local alignOrientation

local grabEvent = ReplicatedStorage.RemoteEvents.Grabbing
local ungrabEvent = ReplicatedStorage.RemoteEvents.Ungrabbing
local dragEvent = ReplicatedStorage.RemoteEvents.Dragging

grabEvent.OnServerEvent:Connect(function(player, initialCFrame, target)
	
	
	holdPoint = Instance.new("Attachment")
	holdPoint.Parent = target
	holdPoint.WorldCFrame = initialCFrame
	
	alignPosition = Instance.new("AlignPosition")
	alignPosition.Mode = Enum.PositionAlignmentMode.OneAttachment
	alignPosition.Parent = target
	alignPosition.MaxForce = 100000
	alignPosition.Responsiveness = 200
	alignPosition.Attachment0 = holdPoint
	
	alignOrientation = Instance.new("AlignOrientation")
	alignOrientation.Mode = Enum.OrientationAlignmentMode.OneAttachment
	alignOrientation.Parent = target
	alignOrientation.MaxTorque = 100000
	alignOrientation.Responsiveness = 50
	alignOrientation.Attachment0 = holdPoint
end)

dragEvent.OnServerEvent:Connect(function(player, cframe)
	alignPosition.Position = cframe.Position
	alignOrientation.CFrame = cframe
end)

ungrabEvent.OnServerEvent:Connect(function(player)
	holdPoint:Destroy()
	alignOrientation:Destroy()
	alignPosition:Destroy()
end)

If first player is holding an object, and then second player tries to hold another object, the first object freezes in air (probably because old alignPosition and alignOrientation constraints are not deleted) and the second object starts following the first player’s mouse position.

This probably happens because the regular script is only one, while there are multiple local scripts that fire the events. But I don’t really know how to fix it, except of making multiple more identical events and scripts for each individual player.

This is the local script btw:

local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ContextActionService = game:GetService("ContextActionService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local CollectionService = game:GetService("CollectionService")

local grabEvent = ReplicatedStorage.RemoteEvents.Grabbing
local ungrabEvent = ReplicatedStorage.RemoteEvents.Ungrabbing
local dragEvent = ReplicatedStorage.RemoteEvents.Dragging
local tagEvent = ReplicatedStorage.RemoteEvents.Tag

local players = game.Players
local localPlayer = players.LocalPlayer
local mouse = localPlayer:GetMouse()
local camera = workspace.CurrentCamera

local highlight = ReplicatedStorage.MinorAssets.PlayersHighlight

local draggable = false

local draggedObject = nil

local rotatingForward
local rotatingBackward
local rotatingRight
local rotatingLeft

local xAngle = 0
local yAngle = 0

local xMax = 180
local xMin = -180
local yMax = 180
local yMin = -180

local function Rotate(actionName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin and inputObject.KeyCode == Enum.KeyCode.W then
		if rotatingBackward ~= nil then
			rotatingBackward:Disconnect()
		end
		rotatingForward = RunService.RenderStepped:Connect(function()
			if xAngle - 1 < -180 then
				xAngle = 180
			else
				xAngle = xAngle - 1
			end
		end)
	elseif inputState == Enum.UserInputState.End and inputObject.KeyCode == Enum.KeyCode.W then
		rotatingForward:Disconnect()
	elseif inputState == Enum.UserInputState.Begin and inputObject.KeyCode == Enum.KeyCode.S then
		if rotatingForward ~= nil then
			rotatingForward:Disconnect()
		end
		rotatingBackward = RunService.RenderStepped:Connect(function()
			if xAngle + 1 > 180 then
				xAngle = -180
			else
				xAngle = xAngle + 1
			end
		end)
	elseif inputState == Enum.UserInputState.End and inputObject.KeyCode == Enum.KeyCode.S then
		rotatingBackward:Disconnect()
	elseif inputState == Enum.UserInputState.Begin and inputObject.KeyCode == Enum.KeyCode.D then
		if rotatingLeft ~= nil then
			rotatingLeft:Disconnect()
		end
		rotatingRight = RunService.RenderStepped:Connect(function()
			if yAngle - 1 < -180 then
				yAngle = 180
			else
				yAngle = yAngle - 1
			end
		end)
	elseif inputState == Enum.UserInputState.End and inputObject.KeyCode == Enum.KeyCode.D then
		rotatingRight:Disconnect()
	elseif inputState == Enum.UserInputState.Begin and inputObject.KeyCode == Enum.KeyCode.A then
		if rotatingRight ~= nil then
			rotatingRight:Disconnect()
		end
		rotatingLeft = RunService.RenderStepped:Connect(function()
			if yAngle + 1 > 180 then
				yAngle = -180
			else
				yAngle = yAngle + 1
			end
		end)
	elseif inputState == Enum.UserInputState.End and inputObject.KeyCode == Enum.KeyCode.A then
		rotatingLeft:Disconnect()
	end
end

local function GetParts(chosenPart)
	local toCheck = {chosenPart}
	local checked = {}

	while #toCheck > 0 do
		for i, part in pairs(toCheck) do
			if table.find(checked, part) then
				continue
			else
				local directlyConnectedParts = part:GetConnectedParts(true)
				local indirectlyConnectedParts = {}

				local joints = part:GetJoints()

				for i, joint in pairs(joints) do
					if joint:IsA("HingeConstraint") or joint:IsA("BallSocketConstraint") then
						local hinge = joint
						if hinge.Attachment0.Parent == part then
							if not table.find(toCheck, hinge.Attachment1.Parent) then
								table.insert(indirectlyConnectedParts, hinge.Attachment1.Parent)
							end
						elseif hinge.Attachment1.Parent == part then
							if not table.find(toCheck, hinge.Attachment0.Parent) then
								table.insert(indirectlyConnectedParts, hinge.Attachment0.Parent)
							end
						end
					end
				end

				for i, con in pairs(indirectlyConnectedParts) do
					table.insert(toCheck, con)
				end

				for i, v in pairs(directlyConnectedParts) do
					if not table.find(toCheck, v) then
						table.insert(toCheck, v)
					end
				end
				table.insert(checked, part)
			end
		end
		if #toCheck == #checked then
			break
		end
	end
	return checked
end

local MapCheck = false
local RangeCheck = false
local AnchorCheck = false
local ButtonCheck = false
local ConnectionsCheck = false
local SeatsCheck = false
local HumanoidCheck = false
local GrabCheck = false

localPlayer.CharacterAdded:Connect(function(character)
	tagEvent:FireServer(character)
end)

RunService.RenderStepped:Connect(function()
	local target = mouse.Target
	highlight.Adornee = target
	
	if target ~= nil then
		
		if target.Parent ~= workspace.Map then
			MapCheck = true
		else
			MapCheck = false
		end
		
		if target:FindFirstAncestorOfClass("Model") ~= nil then
			local model = target:FindFirstAncestorOfClass("Model")
			if model:HasTag("Player") == true or model:HasTag("NPC") == true then
				HumanoidCheck = false
			else
				HumanoidCheck = true
			end
		else
			HumanoidCheck = true
		end
		
		if target:FindFirstChild("AlignPosition") ~= nil then
			GrabCheck = false
		else
			GrabCheck = true
		end
		
		if (localPlayer.Character:FindFirstChild("Head").Position - target.Position).Magnitude <= 20 then
			RangeCheck = true
		else
			RangeCheck = false
		end
		
		if target.Anchored == false then
			AnchorCheck = true
		else
			AnchorCheck = false
		end
		
		if target:FindFirstChild("ClickDetector") == nil then
			ButtonCheck = true
		else
			ButtonCheck = false
		end
		
		local allConnectedParts = GetParts(target)
		local connectedParts = target:GetConnectedParts(true)
		local anchoredConnections = {}
		local occupiedSeats = {}
		
		for i, part in pairs(connectedParts) do
			if part.Anchored == true then
				table.insert(anchoredConnections, part)
			end
		end
		
		if #anchoredConnections == 0 then
			ConnectionsCheck = true
		else
			ConnectionsCheck = false
		end
		
		for i, part in pairs(allConnectedParts) do
			if part:IsA("Seat") or part:IsA("VehicleSeat") then
				if part.Occupant ~= nil then
					table.insert(occupiedSeats, part)
				end
			end
		end
		
		if #occupiedSeats == 0 then
			SeatsCheck = true
		else
			SeatsCheck = false
		end
		
		print(MapCheck, ButtonCheck, AnchorCheck, SeatsCheck, ConnectionsCheck, HumanoidCheck, GrabCheck)
		
		if MapCheck == true and RangeCheck == true and ButtonCheck == true and AnchorCheck == true and SeatsCheck == true and ConnectionsCheck == true and HumanoidCheck == true and GrabCheck == true then
			highlight.Enabled = true
			draggable = true
		else
			highlight.Enabled = false
			draggable = false
		end
	else
		highlight.Enabled = false
		draggable = false
	end
end)

local connection

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		if draggedObject ~= nil then
			ContextActionService:BindAction("Rotating", Rotate, false, Enum.KeyCode.W, Enum.KeyCode.S, Enum.KeyCode.D, Enum.KeyCode.A)
		end
	end
end)

UserInputService.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		if rotatingForward ~= nil then
			rotatingForward:Disconnect()
		end
		if rotatingBackward ~= nil then
			rotatingBackward:Disconnect()
		end
		if rotatingLeft ~= nil then
			rotatingLeft:Disconnect()
		end
		if rotatingRight ~= nil then
			rotatingRight:Disconnect()
		end
		ContextActionService:UnbindAction("Rotating")
	end
end)

UserInputService.InputBegan:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		if draggable == true then
			
			local initialPosition = mouse.Hit.Position
			local initialCFrame = camera.CFrame - camera.CFrame.Position + initialPosition
			local target = mouse.Target
			local distance = (localPlayer.Character:FindFirstChild("Head").Position - initialPosition).Magnitude
			
			draggedObject = target
			
			grabEvent:FireServer(initialCFrame, target)
			
			connection = RunService.RenderStepped:Connect(function()
				
				local direction = mouse.UnitRay.Direction
				local difference = (camera.CFrame.Position - localPlayer.Character:WaitForChild("Head").Position).Magnitude
				local position = Vector3.new(camera.CFrame.Position.X + direction.X * (distance + difference), camera.CFrame.Position.Y + direction.Y * (distance + difference), camera.CFrame.Position.Z + direction.Z * (distance + difference))
				local cframe = camera.CFrame * CFrame.fromAxisAngle(Vector3.new(1, 0, 0), math.rad(xAngle)) * CFrame.fromAxisAngle(Vector3.new(0, 1, 0), math.rad(yAngle)) - camera.CFrame.Position + position
				dragEvent:FireServer(cframe)
			end)
		end
	end
end)

UserInputService.InputEnded:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		ungrabEvent:FireServer()
		connection:Disconnect()
		draggedObject = nil
		xAngle = 0
		yAngle = 0
		if rotatingForward ~= nil then
			rotatingForward:Disconnect()
		end
		if rotatingBackward ~= nil then
			rotatingBackward:Disconnect()
		end
		if rotatingLeft ~= nil then
			rotatingLeft:Disconnect()
		end
		if rotatingRight ~= nil then
			rotatingRight:Disconnect()
		end
		ContextActionService:UnbindAction("Rotating")
	end
end)

Any other solutions?

1 Like

Am I just talking gibberish, I don’t understand.

On the server side the first parameter to your RemoteEvent callback will be the Player which called the event. The script there should store the state of each object in a map from each player to their specific data.

local playersData = {}
grabEvent.OnServerEvent:Connect(function(player, iniitalCFrame, target) 
  local playerData = playersData[player]
  if not playerData then
    playerData = {}
    playersData[player] = playerData
  end
    ... 
end)
2 Likes

Something like this?

grabEvent.OnServerEvent:Connect(function(player, initialCFrame, target)
	local playerData = playersData[player]
	if not playerData then
		playerData = {
			["heldObject"] = target, 
			["holdPoint"] = Instance.new("Attachment"),
			["alignPosition"] = Instance.new("AlignPosition"),
			["alignOrientation"] = Instance.new("AlignOrientation")	
		}
		playersData[player] = playerData
	else
		playerData.heldObject = target
		playerData.holdPoint = Instance.new("Attachment")
		playerData.alignPosition = Instance.new("AlignPosition")
		playerData.alignOrientation = Instance.new("AlignOrientation")
	end
	
	playerData.holdPoint.Parent = target
	playerData.holdPoint.WorldCFrame = initialCFrame
	
	-- and so on
end)

And in the ungrab function I would just destroy the constraints and attachments and set the heldObject to nil? And in the drag function I would just update the alignPosition and alignOrientation properties?

I have tried it myself without waiting for an answer and the result is very cool!
Here is full piece of the code after editing it:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local playersData = {}

local grabEvent = ReplicatedStorage.RemoteEvents.Grabbing
local ungrabEvent = ReplicatedStorage.RemoteEvents.Ungrabbing
local dragEvent = ReplicatedStorage.RemoteEvents.Dragging

grabEvent.OnServerEvent:Connect(function(player, initialCFrame, target)
	local playerData = playersData[player]
	if not playerData then
		playerData = {
			["heldObject"] = target, 
			["holdPoint"] = Instance.new("Attachment"),
			["alignPosition"] = Instance.new("AlignPosition"),
			["alignOrientation"] = Instance.new("AlignOrientation")	
		}
		playersData[player] = playerData
	else
		playerData.heldObject = target
		playerData.holdPoint = Instance.new("Attachment")
		playerData.alignPosition = Instance.new("AlignPosition")
		playerData.alignOrientation = Instance.new("AlignOrientation")
	end
	
	playerData.holdPoint.Parent = target
	playerData.holdPoint.WorldCFrame = initialCFrame
	
	playerData.alignPosition.Mode = Enum.PositionAlignmentMode.OneAttachment
	playerData.alignPosition.Parent = target
	playerData.alignPosition.MaxForce = 100000
	playerData.alignPosition.Responsiveness = 200
	playerData.alignPosition.Attachment0 = playerData.holdPoint
	
	playerData.alignOrientation.Mode = Enum.OrientationAlignmentMode.OneAttachment
	playerData.alignOrientation.Parent = target
	playerData.alignOrientation.MaxTorque = 100000
	playerData.alignOrientation.Responsiveness = 50
	playerData.alignOrientation.Attachment0 = playerData.holdPoint
end)

dragEvent.OnServerEvent:Connect(function(player, cframe)
	local playerData = playersData[player]
	
	playerData.alignPosition.Position = cframe.Position
	playerData.alignOrientation.CFrame = cframe
end)

ungrabEvent.OnServerEvent:Connect(function(player)
	local playerData = playersData[player]
	
	playerData.holdPoint:Destroy()
	playerData.alignOrientation:Destroy()
	playerData.alignPosition:Destroy()
end)
1 Like

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