How would I add a range I can pick things up?

Hello!

So right now, this script can pick up any item named Apple from anywhere if they can click it. How could I add a way to make it only pick things up within a range?

Here’s the script:

local player = game.Players.LocalPlayer 
local mouse = player:GetMouse() 
local camera = workspace.CurrentCamera
local RunService = game:GetService("RunService") 
local UIS = game:GetService("UserInputService")
local target 
local down
mouse.Button1Down:connect(function() 
if mouse.Target.Name == "Apple" then
	if mouse.Target ~= nil and mouse.Target.Locked == false then
		target = mouse.Target 
		mouse.TargetFilter = target 
		down = true 
		target.CanCollide = false

		local gyro = Instance.new("BodyGyro")
		gyro.Name = "Gyro"
		gyro.Parent = target 
		gyro.MaxTorque = Vector3.new(5000000, 5000000, 5000000)
		local force = Instance.new("BodyPosition") 
		force.Name = "Force" 
		force.Parent = target
		force.MaxForce = Vector3.new(100000000000, 100000000000, 100000000000) 
	end
end
end)

game:GetService("RunService").RenderStepped:Connect(function() 
if down == true and target ~= nil then 
	target.Gyro.CFrame = target.CFrame 
	target.Force.Position = camera.CFrame.Position + (mouse.UnitRay.Direction * 5)
end 
end) 

mouse.Button1Up:connect(function() 
if target then
	if target:FindFirstChild("Gyro") or target:FindFirstChild("Force") then 
		target.CanCollide = true
		target.Gyro:Destroy() 
		target.Force:Destroy()
	end
end
down = false
mouse.TargetFilter = nil
target = nil 
end)

Thanks in advance!

1 Like

you can try using Magnitude to get distance from character and item

1 Like

Ah, thank you for this! I’ll read up on this to see what happens!

Or, you can also use Player:DistanceFromCharacter(Vector3)

1 Like

Alright, thank you for this! This will help immensely!