Menu
CoddyTech

Once per Swing

Lesson 4 of 20 in Coddy's Roblox Game: Battlegrounds course.

One swing 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
end

The table is made inside swing, so every swing starts with an empty one, and two enemies in the box are each hit once.

challenge icon

Challenge

Easy

In swing, make local hit = {} before the loop, and hurt a Humanoid only if it is not in hit yet, marking it when you do.

Press Play, 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")
		if humanoid then
			humanoid:TakeDamage(Settings.SwordDamage)
		end
	end
end

-- Every player gets Kills on the leaderboard, and a sword every life
Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local kills = Instance.new("IntValue")
	kills.Name = "Kills"
	kills.Parent = leaderstats

	player.CharacterAdded:Connect(function()
		local sword = ServerStorage.Sword:Clone()
		sword.Parent = player.Backpack
		sword.Activated:Connect(function()
			swing(player)
		end)
	end)
end)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Roblox Game: Battlegrounds