For some reason, my touch function keeps being fired when touching the ball, even though I’m not using the key bind. This only happens after I click the key bind once. Basically I only want the function to fire when the player presses a keybind.
This is what my scripts look like.
Keybind script
local Player = game.Players.LocalPlayer
local uis = game:GetService("UserInputService")
local rp = game:GetService("ReplicatedStorage")
local Set = game:GetService("ReplicatedStorage").Events.Set
uis.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.F then
Set:FireServer()
end
end)
Touch function
local rp = game:GetService("ReplicatedStorage")
local Set = rp:WaitForChild("Events").Set
Set.OnServerEvent:Connect(function(player)
local char = player.Character
local root = char.HumanoidRootPart
local function hit(part)
if part.Name == "volleyball" then
print("test")
local ball = part
local Velocity = Instance.new("BodyVelocity")
local Force = 50
local Direction = root.CFrame.LookVector
ball.CFrame = char.Head.CFrame
Velocity.Parent = ball
Velocity.MaxForce = Vector3.new(1, 1, 1) * math.huge
Velocity.Velocity = (Direction.Unit * Force/3) + Vector3.new(0, Force , 0)
game:GetService("Debris"):AddItem(Velocity, 0.2)
end
end
if player.Backpack.Ready.value == true then
root.Touched:Connect(hit)
end
end)
Your Touched function is never disconnected, read more about connections and disconnections here and use it to implement it when you want the event to be disconnected.
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local root = character:WaitForChild("HumanoidRootPart")
local uis = game:GetService("UserInputService")
local rs = game:GetService("ReplicatedStorage")
local set = rs:WaitForChild("Events"):WaitForChild("Set")
root.Touched:Connect(function(hit)
if not player.Backpack.Ready.Value then
return
end
local keysDown = uis:GetKeysPressed()
for _, key in ipairs(keysDown) do
if key.KeyCode == Enum.KeyCode.F then
if hit.Name == "volleyball" then
set:FireServer(hit)
end
end
end
end)
local rp = game:GetService("ReplicatedStorage")
local set = rs:WaitForChild("Events"):WaitForChild("Set")
set.OnServerEvent:Connect(function(plr, part)
local bv = Instance.new("BodyVelocity")
bv.Parent = part
local direction = plr.Character.HumanoidRootPart.CFrame.LookVector
part.CFrame = plr.Character.Head.CFrame
bv.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
bv.Velocity = (direction.Unit * 50/3) + Vector3.new(0, 50, 0)
game:GetService("Debris"):AddItem(bv, 0.2)
end)