Menu
CoddyTech

Hitbox

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

A swing has to hit something. The question "what is in front of me?" is a spatial query: workspace:GetPartBoundsInBox takes a box (a CFrame for its centre and a Vector3 for its size) and returns every part that overlaps it.

local box = root.CFrame * CFrame.new(0, 0, -3) -- 3 studs in front
local parts = workspace:GetPartBoundsInBox(box, Settings.HitboxSize, params)

A part's model holds the Humanoid, so part.Parent:FindFirstChildOfClass("Humanoid") says whether it belongs to someone who can be hurt.

Your own arms are in that box too. OverlapParams filter the query: with your character in FilterDescendantsInstances, the box never finds your own body.

challenge icon

Challenge

Easy

At the end of swing:

  1. Make OverlapParams that leave out the player's character.
  2. For every part in GetPartBoundsInBox of a box 3 studs in front of the root, sized Settings.HitboxSize: if its parent has a Humanoid, TakeDamage(Settings.SwordDamage).

Press Play and hit the training dummy. 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, at most once per SwingCooldown
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()
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