Once per Swing
Lesson 4 of 25 in Coddy's Roblox Game: Battlegrounds course.
One swing printed three lines and took 30 from the dummy. Its root, legs and head are three parts, all in the box, and each one hurt the same Humanoid.
A table fixes it: remember every Humanoid this swing has hit, and skip one you have seen. A table's keys can be instances:
local hit = {}
if humanoid and not hit[humanoid] then
hit[humanoid] = true
-- hurt it, once
endThe table is made inside swing, so every swing starts with an empty one, and two enemies in the box are each hit once.
Challenge
EasyHit each enemy once per swing.
- In
swing, addlocal hit = {}before the loop. - Hurt a Humanoid only
if humanoid and not hit[humanoid], and sethit[humanoid] = truewhen you do.
Press Play and hit the dummy: the Output shows Dummy is at 90, once. Then Check.
Try it yourself
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)
local lastSwing = {} -- player -> when they last swung
-- Roblox's own sword animations
local slash = Instance.new("Animation")
slash.AnimationId = "rbxassetid://522635514"
print("Swords deal " .. Settings.SwordDamage .. " damage")
-- A swing: the animation, then everyone in the box in front of you is hit
local function swing(player)
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if not root or character.Humanoid.Health <= 0 then
return
end
local now = time()
if lastSwing[player] and now - lastSwing[player] < Settings.SwingCooldown then
return
end
lastSwing[player] = now
character.Humanoid.Animator:LoadAnimation(slash):Play()
-- the box in front of you, never your own body
local params = OverlapParams.new()
params.FilterDescendantsInstances = { character }
local box = root.CFrame * CFrame.new(0, 0, -3)
for _, part in workspace:GetPartBoundsInBox(box, Settings.HitboxSize, params) do
local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
-- Lesson 4: Once per Swing goes here
if humanoid then
humanoid:TakeDamage(Settings.SwordDamage)
print(humanoid.Parent.Name .. " is at " .. humanoid.Health)
end
end
end
-- Every player gets a sword every life
Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function()
local sword = ServerStorage.Sword:Clone()
sword.Parent = player.Backpack
sword.Activated:Connect(function()
swing(player)
end)
end)
end)
All lessons in Roblox Game: Battlegrounds
Practice on your own: Roblox playground