Menu
CoddyTech

电池

Coddy Roblox 游戏:逃离黑暗 课程的第 17 课,共 25 课。

永远亮着的手电筒让黑暗不再难以应对。现在它有一个 Battery,这是工具的一个属性,取值范围从 0 到 Settings.BatteryMax。光束亮着时,每秒会消耗 Settings.BatteryDrain。电量耗尽后,光束会熄灭,而且无法再次开启。

服务器上的一个循环会为每个被拿着且亮着的手电筒消耗电量,每秒执行四次,因此每次循环消耗的电量相当于四分之一秒的用量:

local battery = math.max(0, flashlight:GetAttribute("Battery") - Settings.BatteryDrain * 0.25)

电量是一个属性,因此玩家的 LocalScript 可以读取它,并在 HUD 上显示。math.floor 会去掉小数部分:87.5 会显示为 87。

challenge icon

挑战

困难

手电筒使用电池供电。

  1. 将每个新手电筒的 Battery 属性设为 Settings.BatteryMax;只有电池还有电时,点击才能打开手电筒。
  2. 使用 task.spawn 循环:每隔 0.25 秒,从每个正在手持且已点亮的手电筒中扣除 Settings.BatteryDrain * 0.25;电量降到 0 时,光束会熄灭。
  3. 在 DarkClient 的 RunService.Heartbeat 中,使用 math.floor 在 hud.Battery 中显示 Battery 76%。

点击“运行”并打开手电筒:HUD 上的电量会倒计时。然后点击“检查”。

亲手试试

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 rooms = workspace.Rooms
local lastRoom = rooms.Lobby -- 最新的房间
local count = 0 -- 到目前为止创建的房间数
local monster = nil

-- 夜幕降临:没有阳光,四处只有微弱的光,还起了雾
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

-- 第 17 课:在这里添加电池功能

-- 让门绕着铰链转动打开
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("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
	-- 保留最新的房间,以及它后面的 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)

-- 每位玩家:排行榜上显示 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.Parent = player.Backpack
		local beam = flashlight.Handle.Beam
		flashlight.Activated:Connect(function()
			beam.Enabled = not beam.Enabled
		end)
	end)
end)

Roblox 游戏:逃离黑暗中的所有课

自己练习: Roblox 在线编辑器