How to keep icon position when it changes its parent

I want to make an inventory system where you drag tools to slots, but because it changes its parents every time you drag it, it changes position too. I want to make it stay like it would if it was in the previous parent.

robloxapp-20240624-2036230.wmv (231.6 KB)

Here is the script


local frame = script.Parent.ToolIcon



local oldparent = frame.Parent

local dragToggle = nil

local dragSpeed = 0.25

local dragStart = nil

local startPos = nil

local startloc = frame.Position


local function updateInput(input)

	local delta = input.Position - dragStart

	local position = UDim2.new(startPos.X.Scale, startPos.X.Offset + delta.X,

		startPos.Y.Scale, startPos.Y.Offset + delta.Y)

	game:GetService('TweenService'):Create(frame, TweenInfo.new(dragSpeed), {Position = position}):Play()

end



frame.InputBegan:Connect(function(input)

	if (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch) then 

		dragToggle = true

		dragStart = input.Position
		
		startPos = frame.Position
		if frame.Parent.Parent.Name == "Backpack" then
			
		
		frame.Parent = script.Parent.Parent.Parent
		
			
			
		
		end
		input.Changed:Connect(function()

			if input.UserInputState == Enum.UserInputState.End then

				dragToggle = false
				

			end

		end)

	end

end)



UIS.InputChanged:Connect(function(input)

	if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch then

		if dragToggle then

			updateInput(input)
			
		end

	end

end)

while wait(0.1) do
if dragToggle == false then
		frame.Position = startloc
		
		frame.Parent = oldparent
		
end
end

if script.Parent.Parent.Name == "Backpack" then
	for i, button in pairs(script.Parent.Parent.Parent.Inventory.Slots:GetDescendants()) do
		if button:IsA("ImageButton") then
			button.MouseButton1Click:Connect(function()
				if dragToggle == true then
					button.Name = oldparent.Name
					button.Image = frame.Image
				end
			end)
		end
	end
end

When the player starts dragging, change the Udim2 of the object to the position of the mouse in pixels (set both scales to 0) then once the object has reached a slot and the player lets go of their mouse, set the parent of the object to the new slot and change the object position to the center of that slot in scale.

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