local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local pickupDistance = 5 -- How close the player must be to pick up the object
local holdingItem = nil -- Stores the currently held item
local holdingWeld = nil -- Stores the weld constraint
-- Function to find the closest object
local function findClosestItem(player)
local character = player.Character
if not character then return end
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
if not humanoidRootPart then return end
local closestItem = nil
local minDistance = pickupDistance
for _, item in pairs(workspace:GetChildren()) do
if item:IsA("Model") and item.PrimaryPart and item:FindFirstChild("CanBePickedUp") then
local distance = (humanoidRootPart.Position - item.PrimaryPart.Position).Magnitude
if distance < minDistance then
closestItem = item
minDistance = distance
end
end
end
return closestItem
end
-- Function to play a unique sound for each model
local function playSound(item)
local sound = item:FindFirstChild("PickupSound")
if sound and sound:IsA("Sound") then
sound:Play()
end
end
-- Function to pick up an item
local function pickUpItem(player, item)
if not item or holdingItem then return end
local character = player.Character
if not character then return end
local rightHand = character:FindFirstChild("RightHand") or character:FindFirstChild("Right Arm")
if not rightHand then return end
item.PrimaryPart.Anchored = false
item.Parent = character
holdingItem = item
holdingWeld = Instance.new("Motor6D")
holdingWeld.Part0 = rightHand
holdingWeld.Part1 = item.PrimaryPart
holdingWeld.C0 = CFrame.new(0, 0, -1) -- Position the item in front of the hand
holdingWeld.Parent = rightHand
playSound(item)
end