Hello Robloxians,
I am making a game in roblox using swords, I made my own sword before but noticed one problem that it is damage players when not used, so I decided to use Roblox classic sword to test and edit but experienced same problem again.
Can anyone tell me how do I make this sword work in that way? I have tried to look for solutions but none of them help much.
This is pretty easy, just start a sword.Touched connection whenever the tool is used and add all parts that are touched by the sword to a table. After the attack animation is done, disconnect the sword.Touched connection and apply the damage if there is a player part in the table of touched parts.
local touchedConnection
local attackLenght = 1 --1 second is the duration of the attack
local damage = 20 -- 20 health removed when hit
local sword = script.Parent -- change this to whatever the blade part is
function attack()
local hitHumanoids = {}
touchedConnection = sword.Touched:Connect(function(part)
local humanoid = part.Parent:FindFirstChild("Humanoid")
local canHit = true
if humanoid then
for i,v in pairs(hitHumanoids) do
if v == humanoid
canHit = false
end
end
if canHit then
table.insert(hitHumanoids,humanoid)
humanoid:TakeDamage(damage)
end
end
end)
task.wait(attackLenght)
touchedConnection:Disconnect()
end
This code will basically check if the blade touches a player, apply the damage and put him in a blacklist so the player doesnt get the damage twice.