Hitbox
Lesson 3 of 25 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
EasyMake a swing hurt whoever stands in front of you.
- At the end of
swing, makeOverlapParamswithFilterDescendantsInstances = { character }. - For each part in
GetPartBoundsInBoxofroot.CFrame * CFrame.new(0, 0, -3), sizeSettings.HitboxSize: if its parent has a Humanoid,TakeDamage(Settings.SwordDamage). - Then
print(humanoid.Parent.Name .. " is at " .. humanoid.Health).
Press Play and hit the dummy: the Output counts its health down. 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()
-- Lesson 3: Hitbox goes here
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