Roblox · Приключение · урок 3
Гоблины, которые замечают игрока, бегут к нему и бьют. Если никого нет — возвращаются на место.
Синим — что добавляем на этом уроке.
Workspace └─ Enemies (Folder) └─ Goblin (Model) — Rig Builder R15 ├─ Humanoid (Humanoid) — MaxHealth 60, WalkSpeed 12 └─ EnemyScript (Script)
Где: Workspace → Enemies → Goblin · Script
Зачем: Поиск цели, погоня и удары.
-- игроки
local Players = game:GetService("Players")
-- модель противника
local enemy = script.Parent
-- Humanoid
local humanoid = enemy:WaitForChild("Humanoid")
-- центр
local root = enemy:WaitForChild("HumanoidRootPart")
-- Animator
local animator = humanoid:FindFirstChildOfClass("Animator") or Instance.new("Animator", humanoid)
-- видит игроков ближе 40 studs
local SIGHT = 40
-- бьёт ближе 5 studs
local ATTACK_RANGE = 5
-- урон
local DAMAGE = 10
-- секунд между ударами
local COOLDOWN = 1
-- ходьба
local walkAnim = Instance.new("Animation")
-- стандартная R15
walkAnim.AnimationId = "rbxassetid://507777826"
-- удар
local attackAnim = Instance.new("Animation")
-- стандартный взмах R15
attackAnim.AnimationId = "rbxassetid://522635514"
-- загружаем
local walkTrack = animator:LoadAnimation(walkAnim)
-- по кругу
walkTrack.Looped = true
-- загружаем
local attackTrack = animator:LoadAnimation(attackAnim)
-- поверх ходьбы
attackTrack.Priority = Enum.AnimationPriority.Action
-- куда возвращаться
local home = root.Position
-- время прошлого удара
local lastAttack = 0
-- физику считает сервер
pcall(function() root:SetNetworkOwner(nil) end)
-- скорость изменилась
humanoid.Running:Connect(function(speed)
-- пошёл
if speed > 0.5 and not walkTrack.IsPlaying then
-- шагаем
walkTrack:Play()
-- встал
elseif speed <= 0.5 and walkTrack.IsPlaying then
-- стоим
walkTrack:Stop()
-- конец проверки
end
-- конец функции
end)
-- ближайший живой видимый игрок
local function FindTarget()
-- пока никого
local best, bestRoot, bestDistance = nil, nil, SIGHT
-- все игроки
for _, player in ipairs(Players:GetPlayers()) do
-- персонаж
local character = player.Character
-- его Humanoid
local target = character and character:FindFirstChildOfClass("Humanoid")
-- его центр
local targetRoot = character and character:FindFirstChild("HumanoidRootPart")
-- жив и не невидим
if target and targetRoot and target.Health > 0 and not character:GetAttribute("Invisible") then
-- расстояние
local distance = (targetRoot.Position - root.Position).Magnitude
-- ближе прошлого
if distance < bestDistance then
-- запоминаем
best, bestRoot, bestDistance = target, targetRoot, distance
-- конец проверки
end
-- конец проверки
end
-- конец перебора
end
-- цель, её центр, расстояние
return best, bestRoot, bestDistance
-- конец функции
end
-- пока жив
while humanoid.Health > 0 do
-- ищем цель
local target, targetRoot, distance = FindTarget()
-- нашли
if target then
-- идём к ней
humanoid:MoveTo(targetRoot.Position)
-- рядом и удар готов
if distance <= ATTACK_RANGE and os.clock() - lastAttack >= COOLDOWN then
-- запоминаем время
lastAttack = os.clock()
-- взмах
attackTrack:Play()
-- урон (ForceField защищает)
target:TakeDamage(DAMAGE)
-- конец проверки
end
-- никого рядом
else
-- возвращаемся на место
humanoid:MoveTo(home)
-- конец проверки
end
-- 5 раз в секунду
task.wait(0.2)
-- конец цикла
endЗапусти Play (или Run) и убедись:
Roblox · Adventure · lesson 3
Goblins that spot the player, run to them and attack. If nobody's around, they go back to their place.
Blue — what we add in this lesson.
Workspace └─ Enemies (Folder) └─ Goblin (Model) — Rig Builder R15 ├─ Humanoid (Humanoid) — MaxHealth 60, WalkSpeed 12 └─ EnemyScript (Script)
Where: Workspace → Enemies → Goblin · Script
Why: Finding a target, chasing and hitting.
-- players
local Players = game:GetService("Players")
-- the enemy model
local enemy = script.Parent
-- Humanoid
local humanoid = enemy:WaitForChild("Humanoid")
-- the center
local root = enemy:WaitForChild("HumanoidRootPart")
-- Animator
local animator = humanoid:FindFirstChildOfClass("Animator") or Instance.new("Animator", humanoid)
-- sees players closer than 40 studs
local SIGHT = 40
-- hits closer than 5 studs
local ATTACK_RANGE = 5
-- damage
local DAMAGE = 10
-- seconds between hits
local COOLDOWN = 1
-- walking
local walkAnim = Instance.new("Animation")
-- the standard R15 one
walkAnim.AnimationId = "rbxassetid://507777826"
-- a hit
local attackAnim = Instance.new("Animation")
-- the standard R15 swing
attackAnim.AnimationId = "rbxassetid://522635514"
-- load it
local walkTrack = animator:LoadAnimation(walkAnim)
-- looped
walkTrack.Looped = true
-- load it
local attackTrack = animator:LoadAnimation(attackAnim)
-- over walking
attackTrack.Priority = Enum.AnimationPriority.Action
-- where to return
local home = root.Position
-- the time of the last hit
local lastAttack = 0
-- the server runs the physics
pcall(function() root:SetNetworkOwner(nil) end)
-- the speed changed
humanoid.Running:Connect(function(speed)
-- started walking
if speed > 0.5 and not walkTrack.IsPlaying then
-- walk
walkTrack:Play()
-- stopped
elseif speed <= 0.5 and walkTrack.IsPlaying then
-- stand
walkTrack:Stop()
-- end of check
end
-- end of function
end)
-- the nearest living visible player
local function FindTarget()
-- nobody yet
local best, bestRoot, bestDistance = nil, nil, SIGHT
-- all players
for _, player in ipairs(Players:GetPlayers()) do
-- the character
local character = player.Character
-- their Humanoid
local target = character and character:FindFirstChildOfClass("Humanoid")
-- its center
local targetRoot = character and character:FindFirstChild("HumanoidRootPart")
-- alive and not invisible
if target and targetRoot and target.Health > 0 and not character:GetAttribute("Invisible") then
-- the distance
local distance = (targetRoot.Position - root.Position).Magnitude
-- closer than the previous
if distance < bestDistance then
-- remember
best, bestRoot, bestDistance = target, targetRoot, distance
-- end of check
end
-- end of check
end
-- end of loop
end
-- the target, its center, the distance
return best, bestRoot, bestDistance
-- end of function
end
-- while alive
while humanoid.Health > 0 do
-- look for a target
local target, targetRoot, distance = FindTarget()
-- found
if target then
-- walk to it
humanoid:MoveTo(targetRoot.Position)
-- close and ready to hit
if distance <= ATTACK_RANGE and os.clock() - lastAttack >= COOLDOWN then
-- remember the time
lastAttack = os.clock()
-- the swing
attackTrack:Play()
-- damage (a ForceField protects)
target:TakeDamage(DAMAGE)
-- end of check
end
-- nobody nearby
else
-- go back to the start
humanoid:MoveTo(home)
-- end of check
end
-- 5 times a second
task.wait(0.2)
-- end of loop
endPress Play (or Run) and make sure: