Hello fellow devforum users! I made a hitbox script that works nearly flawlessly. The one flaw is the fact that when you hit an opponent, the opponent plays an animation showing they were punched. Worked fine until I realized that when you walked away from the recently punched opponent and start punching again, the opponent still plays the animation event when they are not being punched. I tried rewriting the code to use .Touched instead of GetPartsInPart(), but that was a horrible idea. Thanks in advanced!
local event = game.ReplicatedStorage.Remotes.HitBoxEvent
local plrs = game:GetService("Players")
local plr = plrs:GetPlayers()[1] or plrs.PlayerAdded:Wait()
local dmg = 2
local touched = false
event.OnServerEvent:Connect(function()
local Hitbox = Instance.new("Part", workspace)
Hitbox.CFrame = plr.Character.HumanoidRootPart.CFrame * CFrame.new(0, 0, -2)
Hitbox.Transparency = 1
Hitbox.Size = Vector3.new(5, 5, 3)
Hitbox.CanCollide = false
Hitbox.Name = plr.Character.Name
local weld = Instance.new("WeldConstraint", Hitbox)
weld.Part1 = plr.Character.HumanoidRootPart
weld.Part0 = Hitbox
local HitChar = {}
task.spawn(function()
for i = 1, 5 do
local parts = workspace:GetPartsInPart(Hitbox)
for _, part in ipairs(parts) do
local character = part:FindFirstAncestorOfClass("Model")
local function hit1()
local anim = character.Humanoid:LoadAnimation(script.Hit1)
anim:Play()
game.Debris:AddItem(anim, .1)
end
local function hit2()
local anim = character.Humanoid:LoadAnimation(script.Hit2)
anim:Play()
game.Debris:AddItem(anim, .1)
end
local function hit3()
local anim = character.Humanoid:LoadAnimation(script.Hit3)
anim:Play()
game.Debris:AddItem(anim, .1)
end
if character and character:FindFirstChild("Humanoid") and not table.find(HitChar, character) and not touched and not (character.Name == Hitbox.Name) then
touched = true
local sound = script.Punch:Clone()
local hitVFX = game.ReplicatedStorage.HitVFX.NormalHit:Clone()
local sound2 = script.Woosh:Clone()
sound2.Parent = plr.Character.HumanoidRootPart
sound2:Play()
game.Debris:AddItem(sound2, 1.321)
game.ReplicatedStorage.Remotes.HitEvent1.OnServerEvent:Connect(hit1)
game.ReplicatedStorage.Remotes.HitEvent2.OnServerEvent:Connect(hit2)
game.ReplicatedStorage.Remotes.HitEvent3.OnServerEvent:Connect(hit3)
hitVFX.Parent = workspace
hitVFX.CFrame = character.HumanoidRootPart.CFrame
sound.Parent = character.HumanoidRootPart
sound:Play()
game.Debris:AddItem(sound, .758)
game.Debris:AddItem(hitVFX, .1)
table.insert(HitChar, character)
character.Humanoid:TakeDamage(dmg)
if character.Humanoid.Health <= 0 and not character:FindFirstChild("NPC") then
plr.leaderstats.Cash.Value += 10
end
end
end
end
task.wait(.1)
Hitbox:Destroy()
end)
task.wait(.1)
touched = false
end)