I want to achieve a system where you can press E in front of an item and it’ll hover in front of you until you press E again, which then It’ll drop onto the ground.
I used to use drag detectors for this which worked fine, but they were ultimately extremely tedious and were a nightmare for mobile users.
First, ensure that the item you want to hover is a Part in your game.
Step 2: Creating a Local Script
Create a LocalScript inside the StarterPlayerScripts to handle the key press and item movement.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local HoverItem = nil
local Hovering = false
local HoverDistance = 5
-- Function to toggle the hovering state
local function toggleHover()
Hovering = not Hovering
if not Hovering and HoverItem then
HoverItem.Anchored = false
HoverItem = nil
end
end
-- Function to update the hover position
local function updateHover()
if Hovering and HoverItem then
local character = LocalPlayer.Character
if character then
local rootPart = character:FindFirstChild("HumanoidRootPart")
if rootPart then
local hoverPosition = rootPart.CFrame * CFrame.new(0, 0, -HoverDistance)
HoverItem.CFrame = hoverPosition
end
end
end
end
-- Key press event handler
UserInputService.InputBegan:Connect(function(input, gameProcessed)
if gameProcessed then return end
if input.KeyCode == Enum.KeyCode.E then
if Hovering then
toggleHover()
else
local character = LocalPlayer.Character
if character then
local rootPart = character:FindFirstChild("HumanoidRootPart")
if rootPart then
local hoverPosition = rootPart.CFrame * CFrame.new(0, 0, -HoverDistance)
local parts = game.Workspace:FindPartsInRegion3(Region3.new(hoverPosition.Position - Vector3.new(2, 2, 2), hoverPosition.Position + Vector3.new(2, 2, 2)))
for _, part in ipairs(parts) do
if part.Name == "HoverItem" then
HoverItem = part
HoverItem.Anchored = true
toggleHover()
break
end
end
end
end
end
end
end)
-- Update hover position each frame
game:GetService("RunService").RenderStepped:Connect(updateHover)