冲刺
Coddy Roblox 游戏:逃离黑暗 课程的第 21 课,共 25 课。
有时你得跑起来。按住 Shift(或手机上的按钮),只要还有体力,就会以 Settings.SprintSpeed 的速度冲刺:冲刺时体力会消耗,走路时体力会恢复。体力耗尽后,冲刺会停止,直到你再次按下按钮。
这一切都在客户端完成。玩家自己的角色归自己控制:Roblox 允许 LocalScript 设置其 Humanoid 的 WalkSpeed,角色就会按设定移动。ContextActionService 会告诉脚本按键何时按下(Begin)和松开(End):
ContextActionService:BindAction("Sprint", function(_, state)
sprinting = state == Enum.UserInputState.Begin
end, true, Enum.KeyCode.LeftShift)每一帧中,dt 表示距上一帧经过的秒数,因此体力的变化量等于体力变化速率乘以 dt。
挑战
困难按住 Shift 冲刺,直到体力耗尽。
- 在
DarkClient中,维护sprinting和stamina(取自Settings.StaminaMax);将"Sprint"绑定到LeftShift,并添加触摸按钮。 - 在 Heartbeat 中,体力充足时冲刺:扣除
Settings.StaminaDrain * dt,将 WalkSpeed 设为Settings.SprintSpeed;体力降至 0 时停止冲刺。 - 否则,补充
Settings.StaminaRegen * dt,直到体力达到上限,并将 WalkSpeed 设为Settings.WalkSpeed。根据体力设置hud.Stamina.Fill的大小。
按“开始”并按住 Shift:你会开始奔跑,体力条也会逐渐耗尽。然后按“检查”。
亲手试试
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Lighting = game:GetService("Lighting")
local TweenService = game:GetService("TweenService")
local PathfindingService = game:GetService("PathfindingService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local rooms = workspace.Rooms
local lastRoom = rooms.Lobby -- 最新的房间
local count = 0 -- 到目前为止创建的房间数
local monster = nil
local codes = {} -- 金库门 -> 对应的密码
local lastTry = {} -- 玩家 -> 上次尝试输入密码的时间
-- 夜幕降临:没有阳光,四周只有微光,还有雾
Lighting.ClockTime = Settings.ClockTime
Lighting.Ambient = Settings.Ambient
Lighting.OutdoorAmbient = Settings.Ambient
Lighting.FogColor = Color3.new(0, 0, 0)
Lighting.FogEnd = Settings.FogEnd
print("Lights out")
-- 玩家携带的工具:在手里或 Backpack 中
local function findTool(player, name)
return (player.Character and player.Character:FindFirstChild(name)) or player.Backpack:FindFirstChild(name)
end
-- 手电筒亮着时会耗电,电量用尽就会熄灭
task.spawn(function()
while true do
task.wait(0.25)
for _, player in Players:GetPlayers() do
local flashlight = player.Character and player.Character:FindFirstChild("Flashlight")
if flashlight and flashlight.Handle.Beam.Enabled then
local battery = math.max(0, flashlight:GetAttribute("Battery") - Settings.BatteryDrain * 0.25)
flashlight:SetAttribute("Battery", battery)
if battery == 0 then
flashlight.Handle.Beam.Enabled = false
end
end
end
end
end)
-- 让门绕着铰链转开
local function openDoor(door)
door:SetAttribute("Open", true)
door.Panel.Prompt.Enabled = false
local hinge, panel = door.Hinge, door.Panel
local goal = hinge.CFrame * CFrame.Angles(0, math.rad(90), 0) * hinge.CFrame:ToObjectSpace(panel.CFrame)
TweenService:Create(panel, TweenInfo.new(0.6), { CFrame = goal }):Play()
end
-- MonsterSight 范围内最近的、还活着且没有躲藏的玩家,以及距离
local function nearestCharacter(position)
local best, bestDistance = nil, Settings.MonsterSight
for _, player in Players:GetPlayers() do
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if root and character.Humanoid.Health > 0 and not character:GetAttribute("Hidden") then
local distance = (root.Position - position).Magnitude
if distance < bestDistance then
best, bestDistance = character, distance
end
end
end
return best, bestDistance
end
-- 怪物能看到这个角色吗?从它头部射出的射线会击中这个角色
local function canSee(shadow, character)
local from = shadow.Head.Position
local params = RaycastParams.new()
params.FilterDescendantsInstances = { shadow }
local hit = workspace:Raycast(from, character.HumanoidRootPart.Position - from, params)
return hit ~= nil and hit.Instance:IsDescendantOf(character)
end
-- 走向目标点:路畅通时直走,否则沿路径走
local function walkToward(shadow, goal, path)
local root = shadow.HumanoidRootPart
local params = RaycastParams.new()
params.FilterDescendantsInstances = { shadow }
local hit = workspace:Raycast(root.Position, goal - root.Position, params)
if not hit or hit.Instance.Parent:FindFirstChildOfClass("Humanoid") then
shadow.Humanoid:MoveTo(goal)
return
end
path:ComputeAsync(root.Position, goal)
local points = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success and points[2] then
shadow.Humanoid:MoveTo(points[2].Position)
end
end
-- 玩家所在房间往前数 `back` 个房间的中心(也就是那个
-- 最新房间之前),供怪物巡逻
local function patrolPoint(back)
for _, room in rooms:GetChildren() do
if room:GetAttribute("Number") == count - 1 - back then
return (room.Entrance.CFrame * CFrame.new(0, 3.1, -12)).Position
end
end
return nil
end
-- 怪物的行动逻辑:每隔四分之一秒追踪玩家
local function runMonster(shadow)
local humanoid = shadow.Humanoid
local root = shadow.HumanoidRootPart
local path = PathfindingService:CreatePath()
local lastSeen = nil -- 它上次看到玩家的位置
local back = 0 -- 巡逻位置:0 表示玩家所在的房间,2 表示往回数两个房间
while shadow.Parent do
local character = nearestCharacter(root.Position)
if character and canSee(shadow, character) then
lastSeen = character.HumanoidRootPart.Position
else
character = nil
end
if character and (character.HumanoidRootPart.Position - root.Position).Magnitude <= Settings.CatchDistance then
-- 抓到了:玩家被击败,怪物消失,直到下一扇门才会再出现
character.Humanoid.Health = 0
shadow:Destroy()
monster = nil
return
end
local goal = character and character.HumanoidRootPart.Position or lastSeen
if goal then
walkToward(shadow, goal, path)
-- 到了上次看到你的位置,却发现你不在:它放弃追踪
if not character and ((goal - root.Position) * Vector3.new(1, 0, 1)).Magnitude < 1.5 then
lastSeen = nil
end
else
-- 视线中没人:来回巡逻
local point = patrolPoint(back) or patrolPoint(0)
if point then
walkToward(shadow, point, path)
if ((point - root.Position) * Vector3.new(1, 0, 1)).Magnitude < 2 then
back = back == 0 and 2 or 0
end
end
end
task.wait(0.25)
end
end
-- 怪物从你身后出现:在最新房间往回数第二个房间的入口
local function spawnMonster()
local behind = nil
for _, room in rooms:GetChildren() do
if room:GetAttribute("Number") == count - 2 then
behind = room
end
end
if not behind then
return
end
monster = ServerStorage.Shadow:Clone()
monster:PivotTo(behind.Entrance.CFrame + Vector3.new(0, 3.1, 0))
monster.Humanoid.WalkSpeed = Settings.MonsterSpeed
monster.Parent = workspace
task.spawn(runMonster, monster)
end
local addRoom -- 在下方定义:一扇门会添加一个房间,每个房间都有一扇门
-- 玩家打开门时,门会执行的操作
local function setupDoor(door)
door.Panel.Prompt.Triggered:Connect(function(player)
if door:GetAttribute("Open") then
return
end
if door:GetAttribute("Vault") and door:GetAttribute("Locked") then
return -- 在密码键盘上输入密码,才能打开金库
end
if door:GetAttribute("Locked") then
local key = findTool(player, "Key")
if not key then
return
end
key:Destroy()
door:SetAttribute("Locked", nil)
end
if door.Parent == lastRoom then
addRoom()
end
openDoor(door)
end)
end
setupDoor(workspace.Rooms.Lobby.Door)
-- 走进房间:它会成为玩家的 Room 和重生点
local function setupEntry(room)
room.Entry.Touched:Connect(function(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
local number = room:GetAttribute("Number")
player.leaderstats.Room.Value = number
player.RespawnLocation = room.Checkpoint
end
end)
end
setupEntry(workspace.Rooms.Lobby)
-- 衣柜:按 E 躲进去,再按 E 出来
local function setupCloset(closet)
closet.Front.Prompt.Triggered:Connect(function(player)
local character = player.Character
if character:GetAttribute("Hidden") then
character:PivotTo(closet.Front.CFrame * CFrame.new(-3, -1, 0) * CFrame.Angles(0, math.rad(90), 0))
character:SetAttribute("Hidden", nil)
else
character:PivotTo(closet.Inside.CFrame + Vector3.new(0, 2.5, 0))
character:SetAttribute("Hidden", true)
end
end)
end
-- 在最新房间的出口处添加一个新房间
function addRoom()
count += 1
local name = Settings.Order[(count - 1) % #Settings.Order + 1]
if count >= Settings.RoomsToEscape then
name = "Exit"
end
local room = ServerStorage.Rooms[name]:Clone()
room:PivotTo(lastRoom.Exit.CFrame)
room:SetAttribute("Number", count)
room.Sign.SurfaceGui.Number.Text = "Room " .. count
room.Parent = rooms
lastRoom = room
setupDoor(room.Door)
setupEntry(room)
-- 上锁房间的钥匙就在房间里
local keySpot = room:FindFirstChild("KeySpot")
if keySpot then
local key = ServerStorage.Key:Clone()
key.Handle.CFrame = keySpot.CFrame
key.Parent = room
key.Handle.Prompt.Triggered:Connect(function(player)
key.Handle.Prompt.Enabled = false
key.Parent = player.Backpack
end)
end
local closet = room:FindFirstChild("Closet")
if closet then
setupCloset(closet)
end
-- 有些房间里有电池
local batterySpot = room:FindFirstChild("BatterySpot")
if batterySpot then
local battery = ServerStorage.Battery:Clone()
battery.CFrame = batterySpot.CFrame
battery.Parent = room
battery.Prompt.Triggered:Connect(function(player)
local flashlight = findTool(player, "Flashlight")
if flashlight and battery.Parent then
flashlight:SetAttribute("Battery", math.min(Settings.BatteryMax, flashlight:GetAttribute("Battery") + Settings.BatteryRefill))
battery:Destroy()
end
end)
end
-- 保险库的密码写在里面的纸条上
if room.Door:GetAttribute("Vault") then
local code = tostring(math.random(1000, 9999))
codes[room.Door] = code
room.Note.SurfaceGui.Code.Text = "Code " .. code
end
-- 保留最新房间,以及它后面的 KeepRooms 个房间
for _, old in rooms:GetChildren() do
local number = old:GetAttribute("Number")
if number < count - Settings.KeepRooms then
print("Room " .. number .. " is gone")
old:Destroy()
end
end
if count >= Settings.MonsterFrom and not monster then
spawnMonster()
end
return room
end
-- 离开衣柜后,你就不再处于隐藏状态
task.spawn(function()
while true do
task.wait(0.25)
for _, player in Players:GetPlayers() do
local character = player.Character
if character and character:GetAttribute("Hidden") then
local closest = math.huge
for _, inside in workspace.Rooms:GetDescendants() do
if inside.Name == "Inside" then
closest = math.min(closest, (inside.Position - character.HumanoidRootPart.Position).Magnitude)
end
end
if closest > 4 then
character:SetAttribute("Hidden", nil)
end
end
end
end
end)
-- 玩家在保险库的键盘上输入密码。服务器会检查:玩家附近是否有真正的保险库,
-- 每隔 CodeWait 才能尝试一次,以及密码是否正确
remotes.TryCode.OnServerInvoke = function(player, door, code)
if typeof(door) ~= "Instance" or not codes[door] or typeof(code) ~= "string" then
return false
end
local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
if not root or (root.Position - door.Panel.Position).Magnitude > 12 then
return false
end
local now = time()
if lastTry[player] and now - lastTry[player] < Settings.CodeWait then
return false
end
lastTry[player] = now
if code ~= codes[door] then
return false
end
codes[door] = nil
door:SetAttribute("Locked", nil)
if door.Parent == lastRoom then
addRoom()
end
openDoor(door)
return true
end
-- 每位玩家:排行榜上显示 Room,每次重生都会获得手电筒
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local room = Instance.new("IntValue")
room.Name = "Room"
room.Parent = leaderstats
player.CharacterAdded:Connect(function()
local flashlight = ServerStorage.Flashlight:Clone()
flashlight:SetAttribute("Battery", Settings.BatteryMax)
flashlight.Parent = player.Backpack
local beam = flashlight.Handle.Beam
flashlight.Activated:Connect(function()
if beam.Enabled then
beam.Enabled = false
elseif flashlight:GetAttribute("Battery") > 0 then
beam.Enabled = true
end
end)
end)
end)
Roblox 游戏:逃离黑暗中的所有课
自己练习: Roblox 在线编辑器