Swing
Lesson 2 of 20 in Coddy's Roblox Game: Battlegrounds course.
With a tool in hand, a click (or a tap) fires the Tool's Activated event, on the server too. A swing plays Roblox's own sword slash: an Animation names it by its id, and the character's Animator, inside its Humanoid, loads it into a track to play:
local slash = Instance.new("Animation")
slash.AnimationId = "rbxassetid://522635514"
character.Humanoid.Animator:LoadAnimation(slash):Play()Without a limit, a player could click as fast as they like, so a swing remembers when the last one was, per player, in a table, and refuses another within Settings.SwingCooldown seconds.
Challenge
Easy- Near the top, add
local lastSwing = {}and theslashAnimation (idrbxassetid://522635514). - Write
swing(player)above PlayerAdded: return if the player has no living character or swung less thanSettings.SwingCooldownago; otherwise remember the time and play the slash on their Animator. - Where you give the sword, connect its
Activatedtoswing(player).
Press Play, hold the sword and click. Then Check.
Try it yourself
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)
print("Swords deal " .. Settings.SwordDamage .. " damage")
-- 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
end)
end)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.