Une fois par coup
Leçon 4 sur 25 du cours Jeu Roblox : Arène de combat de Coddy.
Un coup a affiché trois lignes et a retiré 30 points au mannequin. Sa racine, ses jambes et sa tête sont trois parties, toutes dans la boîte, et chacune a blessé le même Humanoid.
Une table règle le problème : mémorise chaque Humanoid que ce coup a touché, et ignore ceux que tu as déjà vus. Les clés d’une table peuvent être des instances :
local hit = {}
if humanoid and not hit[humanoid] then
hit[humanoid] = true
-- inflige-lui des dégâts, une seule fois
endLa table est créée dans swing, donc chaque coup commence avec une table vide, et chacun des deux ennemis dans la boîte est touché une seule fois.
Défi
FacileTouche chaque ennemi une seule fois par coup.
- Dans
swing, ajoutelocal hit = {}avant la boucle. - Blesse un Humanoid uniquement avec
if humanoid and not hit[humanoid], et définishit[humanoid] = truelorsque tu le fais.
Clique sur « Jouer » et touche le mannequin : Output affiche Dummy is at 90, une seule fois. Puis clique sur « Vérifier ».
Essayez vous-même
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)
local lastSwing = {} -- player -> moment de son dernier coup d’épée
-- Les animations d’épée propres à Roblox
local slash = Instance.new("Animation")
slash.AnimationId = "rbxassetid://522635514"
print("Swords deal " .. Settings.SwordDamage .. " damage")
-- Un coup d’épée : l’animation, puis tous ceux qui se trouvent dans la zone devant vous sont touchés
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()
-- la zone devant vous, jamais votre propre corps
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")
-- Leçon 4 : Once per Swing se place ici
if humanoid then
humanoid:TakeDamage(Settings.SwordDamage)
print(humanoid.Parent.Name .. " is at " .. humanoid.Health)
end
end
end
-- Chaque joueur reçoit une épée à chaque nouvelle vie
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)
Toutes les leçons de Jeu Roblox : Arène de combat
Entraînez-vous par vous-même : Playground Roblox