So I have a code that checks when you hit the ball in a loop but my problem is that when the variable “hit” is set to false, it starts to run the function multiple times:
local RunService = game:GetService("RunService")
local character = script.Parent
local HumanoidRootPart = character:WaitForChild("HumanoidRootPart")
local Humanoid = character:WaitForChild("Humanoid")
local Animator = Humanoid:WaitForChild("Animator")
local Ball = workspace:WaitForChild("Ball")
local CurrentTarget = Ball:WaitForChild("CurrentTarget")
local HitAnimation = script:WaitForChild("HitAnimation")
local hitDistance = 20
local hit = false
local connection
local blockedConnection
local function ActivateBlocked()
if blockedConnection then
blockedConnection:Disconnect()
blockedConnection = nil
end
blockedConnection = RunService.Heartbeat:Connect(function()
local distance = (HumanoidRootPart.Position - Ball.Position).Magnitude
if distance <= hitDistance and hit then
script.HitBall:FireServer()
hit = false <--------------------------
print("hit")
if blockedConnection then
blockedConnection:Disconnect()
blockedConnection = nil
end
end
end)
end
local function PlayAnimation()
local track = Animator:LoadAnimation(HitAnimation)
track:Play()
track.Ended:Connect(function()
if blockedConnection then
blockedConnection:Disconnect()
blockedConnection = nil
end
--print("ended")
hit = false
end)
end
connection = RunService.Heartbeat:Connect(function()
if CurrentTarget.Value == character and not hit then
local result = PredictBall()
if result then
hit = true
print("Fired", CurrentTarget.Value)
PlayAnimation()
ActivateBlocked()
end
end
end)