Roblox · Хоррор · урок 3
Shift — бег, C — присесть. Скорость меняется всегда, а свои анимации бега и приседа можно добавить, если они у тебя есть.
Синим — что добавляем на этом уроке.
StarterPlayer └─ StarterCharacterScripts — скрипты кладутся в каждого персонажа ├─ RunScript (LocalScript) │ └─ RunAnim (Animation) — AnimationId — по желанию └─ CrouchScript (LocalScript) └─ CrouchAnim (Animation) — AnimationId — по желанию
Где: StarterPlayer → StarterCharacterScripts · LocalScript
Зачем: Бег на Shift.
-- клавиатура
local UIS = game:GetService("UserInputService")
-- скрипт лежит в персонаже
local character = script.Parent
-- Humanoid
local humanoid = character:WaitForChild("Humanoid")
-- проигрывает анимации
local animator = humanoid:WaitForChild("Animator")
-- скорость бега
local RUN_SPEED = 25
-- обычная скорость
local WALK_SPEED = 16
-- Animation внутри скрипта
local runAnim = script:WaitForChild("RunAnim")
-- дорожка анимации (если есть своя)
local runTrack = nil
-- ID вставлен
if runAnim.AnimationId ~= "" then
-- загружаем
runTrack = animator:LoadAnimation(runAnim)
-- важнее обычной ходьбы
runTrack.Priority = Enum.AnimationPriority.Movement
-- по кругу
runTrack.Looped = true
-- конец проверки
end
-- сейчас бежим?
local running = false
-- включает и выключает анимацию бега
local function UpdateAnim()
-- своей анимации нет — бежим стандартной
if not runTrack then return end
-- персонаж двигается
local moving = humanoid.MoveDirection.Magnitude > 0
-- бежим, а анимация не играет
if running and moving and not runTrack.IsPlaying then
-- включаем плавно
runTrack:Play(0.2)
-- остановились
elseif (not running or not moving) and runTrack.IsPlaying then
-- выключаем
runTrack:Stop(0.2)
-- конец проверки
end
-- конец функции
end
-- начать или закончить бег
local function SetRunning(value)
-- погибшие не бегают
if humanoid.Health <= 0 then return end
-- сидим? (ставит скрипт приседания)
local crouching = character:GetAttribute("Crouching")
-- сидя не бегаем
running = value and not crouching
-- скоростью сидя управляет другой скрипт
if not crouching then
-- бег или шаг
humanoid.WalkSpeed = running and RUN_SPEED or WALK_SPEED
-- конец проверки
end
-- анимация
UpdateAnim()
-- конец функции
end
-- нажали клавишу
UIS.InputBegan:Connect(function(input, processed)
-- левый Shift, и не в чате
if not processed and input.KeyCode == Enum.KeyCode.LeftShift then
-- бежим
SetRunning(true)
-- конец проверки
end
-- конец функции
end)
-- отпустили клавишу
UIS.InputEnded:Connect(function(input)
-- это Shift
if input.KeyCode == Enum.KeyCode.LeftShift then
-- идём шагом
SetRunning(false)
-- конец проверки
end
-- конец функции
end)
-- встали или пошли — обновляем анимацию
humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(UpdateAnim)
-- присели во время бега
character:GetAttributeChangedSignal("Crouching"):Connect(function()
-- бег прекращается
if character:GetAttribute("Crouching") then SetRunning(false) end
-- конец функции
end)Где: StarterPlayer → StarterCharacterScripts · LocalScript
Зачем: Присед на C.
-- клавиатура
local UIS = game:GetService("UserInputService")
-- персонаж
local character = script.Parent
-- Humanoid
local humanoid = character:WaitForChild("Humanoid")
-- анимации
local animator = humanoid:WaitForChild("Animator")
-- скорость сидя
local CROUCH_SPEED = 6
-- обычная скорость
local WALK_SPEED = 16
-- Animation внутри скрипта
local crouchAnim = script:WaitForChild("CrouchAnim")
-- дорожка анимации
local track = nil
-- своя анимация есть
if crouchAnim.AnimationId ~= "" then
-- загружаем
track = animator:LoadAnimation(crouchAnim)
-- поверх ходьбы и стояния
track.Priority = Enum.AnimationPriority.Action
-- по кругу
track.Looped = true
-- конец проверки
end
-- сидим?
local crouching = false
-- нажали клавишу
UIS.InputBegan:Connect(function(input, processed)
-- нужна C и не в чате
if processed or input.KeyCode ~= Enum.KeyCode.C then return end
-- погибшие не приседают
if humanoid.Health <= 0 then return end
-- C переключает: сесть / встать
crouching = not crouching
-- сообщаем скрипту бега
character:SetAttribute("Crouching", crouching)
-- сели
if crouching then
-- медленно
humanoid.WalkSpeed = CROUCH_SPEED
-- камера ниже — видно и без анимации
humanoid.CameraOffset = Vector3.new(0, -1.5, 0)
-- анимация приседа
if track then track:Play(0.2) end
-- встали
else
-- обычная скорость
humanoid.WalkSpeed = WALK_SPEED
-- камера на место
humanoid.CameraOffset = Vector3.zero
-- выключаем анимацию
if track then track:Stop(0.2) end
-- конец проверки
end
-- конец функции
end)Запусти Play (или Run) и убедись:
Roblox · Horror · lesson 3
Shift runs, C crouches. The speed always changes, and you can add your own run and crouch animations if you have them.
Blue — what we add in this lesson.
StarterPlayer └─ StarterCharacterScripts — scripts are put into every character ├─ RunScript (LocalScript) │ └─ RunAnim (Animation) — AnimationId — optional └─ CrouchScript (LocalScript) └─ CrouchAnim (Animation) — AnimationId — optional
Where: StarterPlayer → StarterCharacterScripts · LocalScript
Why: Run on Shift.
-- the keyboard
local UIS = game:GetService("UserInputService")
-- the script sits in the character
local character = script.Parent
-- Humanoid
local humanoid = character:WaitForChild("Humanoid")
-- plays animations
local animator = humanoid:WaitForChild("Animator")
-- running speed
local RUN_SPEED = 25
-- normal speed
local WALK_SPEED = 16
-- the Animation inside the script
local runAnim = script:WaitForChild("RunAnim")
-- the animation track (if you have your own)
local runTrack = nil
-- an ID is set
if runAnim.AnimationId ~= "" then
-- load it
runTrack = animator:LoadAnimation(runAnim)
-- takes priority over normal walking
runTrack.Priority = Enum.AnimationPriority.Movement
-- looped
runTrack.Looped = true
-- end of check
end
-- running now?
local running = false
-- turns the run animation on and off
local function UpdateAnim()
-- no animation of our own — use the standard run
if not runTrack then return end
-- the character is moving
local moving = humanoid.MoveDirection.Magnitude > 0
-- running but the animation isn't playing
if running and moving and not runTrack.IsPlaying then
-- start it smoothly
runTrack:Play(0.2)
-- stopped
elseif (not running or not moving) and runTrack.IsPlaying then
-- turn it off
runTrack:Stop(0.2)
-- end of check
end
-- end of function
end
-- start or stop running
local function SetRunning(value)
-- dead characters don't run
if humanoid.Health <= 0 then return end
-- crouching? (set by the crouch script)
local crouching = character:GetAttribute("Crouching")
-- no running while crouching
running = value and not crouching
-- the crouch speed is handled by the other script
if not crouching then
-- run or walk
humanoid.WalkSpeed = running and RUN_SPEED or WALK_SPEED
-- end of check
end
-- the animation
UpdateAnim()
-- end of function
end
-- a key was pressed
UIS.InputBegan:Connect(function(input, processed)
-- left Shift, and not typing in chat
if not processed and input.KeyCode == Enum.KeyCode.LeftShift then
-- run
SetRunning(true)
-- end of check
end
-- end of function
end)
-- a key was released
UIS.InputEnded:Connect(function(input)
-- it's Shift
if input.KeyCode == Enum.KeyCode.LeftShift then
-- walk
SetRunning(false)
-- end of check
end
-- end of function
end)
-- stopped or started moving — update the animation
humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(UpdateAnim)
-- crouched while running
character:GetAttributeChangedSignal("Crouching"):Connect(function()
-- running stops
if character:GetAttribute("Crouching") then SetRunning(false) end
-- end of function
end)Where: StarterPlayer → StarterCharacterScripts · LocalScript
Why: Crouch on C.
-- the keyboard
local UIS = game:GetService("UserInputService")
-- the character
local character = script.Parent
-- Humanoid
local humanoid = character:WaitForChild("Humanoid")
-- animations
local animator = humanoid:WaitForChild("Animator")
-- crouching speed
local CROUCH_SPEED = 6
-- normal speed
local WALK_SPEED = 16
-- the Animation inside the script
local crouchAnim = script:WaitForChild("CrouchAnim")
-- the animation track
local track = nil
-- there is an animation of our own
if crouchAnim.AnimationId ~= "" then
-- load it
track = animator:LoadAnimation(crouchAnim)
-- over walking and standing
track.Priority = Enum.AnimationPriority.Action
-- looped
track.Looped = true
-- end of check
end
-- crouching?
local crouching = false
-- a key was pressed
UIS.InputBegan:Connect(function(input, processed)
-- needs C and not typing in chat
if processed or input.KeyCode ~= Enum.KeyCode.C then return end
-- dead characters don't crouch
if humanoid.Health <= 0 then return end
-- C toggles: crouch / stand
crouching = not crouching
-- tell the run script
character:SetAttribute("Crouching", crouching)
-- crouched
if crouching then
-- slowly
humanoid.WalkSpeed = CROUCH_SPEED
-- the camera goes lower — noticeable even without an animation
humanoid.CameraOffset = Vector3.new(0, -1.5, 0)
-- the crouch animation
if track then track:Play(0.2) end
-- stood up
else
-- normal speed
humanoid.WalkSpeed = WALK_SPEED
-- camera back in place
humanoid.CameraOffset = Vector3.zero
-- turn off the animation
if track then track:Stop(0.2) end
-- end of check
end
-- end of function
end)Press Play (or Run) and make sure: