Lập trình Roblox · Khóa 3: Hệ thống game – xu, cửa hàng
| Ý nghĩa | |
|---|---|
humanoid.Health | máu hiện tại |
humanoid.MaxHealth | máu tối đa (mặc định 100) |
humanoid:TakeDamage(n) | trừ n máu (không tác dụng khi có khiên) |
humanoid.HealthChanged | sự kiện: máu thay đổi, gửi kèm máu mới |
humanoid.Died | sự kiện: nhân vật chết |
local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(nhanVat) local humanoid = nhanVat:WaitForChild("Humanoid") humanoid.MaxHealth = 200 humanoid.Health = 200 end) end)
StarterGui
└── ThanhMauGui (ScreenGui)
└── Nen (Frame: đen, Size {0.3, 0}, {0, 24}, góc dưới giữa)
├── UICorner
├── Mau (Frame: xanh lá, Size {1, 0}, {1, 0})
│ └── UICorner
└── Chu (TextLabel: "100 / 100", nền trong suốt)LocalScript trong ThanhMauGui:
local Players = game:GetService("Players") local player = Players.LocalPlayer local nen = script.Parent.Nen local function theoDoi(nhanVat) local humanoid = nhanVat:WaitForChild("Humanoid") local function capNhat() local tiLe = humanoid.Health / humanoid.MaxHealth nen.Mau.Size = UDim2.new(tiLe, 0, 1, 0) nen.Chu.Text = math.floor(humanoid.Health) .. " / " .. humanoid.MaxHealth end capNhat() humanoid.HealthChanged:Connect(capNhat) end if player.Character then theoDoi(player.Character) end player.CharacterAdded:Connect(theoDoi)
Thêm vào LocalScript:
local StarterGui = game:GetService("StarterGui") StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Health, false)
SetCoreGuiEnabled chỉ dùng trong LocalScriptlocal XANH = Color3.fromRGB(0, 220, 0) local DO = Color3.fromRGB(230, 0, 0) -- trong hàm capNhat, sau khi tính tiLe: nen.Mau.BackgroundColor3 = DO:Lerp(XANH, tiLe)
mauA:Lerp(mauB, t): pha màu – t = 0 là mauA, t = 1 là mauB, t = 0.5 là màu giữalocal Players = game:GetService("Players") local vung = script.Parent -- Part trong suốt, CanCollide tắt while true do for _, player in ipairs(Players:GetPlayers()) do local nhanVat = player.Character local goc = nhanVat and nhanVat:FindFirstChild("HumanoidRootPart") if goc then local khoangCach = (goc.Position - vung.Position).Magnitude if khoangCach < vung.Size.X / 2 then nhanVat.Humanoid:TakeDamage(5) end end end task.wait(1) end
(A - B).Magnitude: khoảng cách giữa hai điểmThanh máu riêng ở góc dưới giữa, hiện chữ "máu / máu tối đa", ẩn thanh máu mặc định.
Thanh máu đổi màu dần xanh → đỏ; mỗi lần mất máu, khung rung nhẹ (Tween Position qua lại).
Khi máu dưới 30%, một khung đỏ trong suốt phủ toàn màn hình nhấp nháy cảnh báo.
| Em gặp | Nguyên nhân |
|---|---|
| Thanh máu không đổi sau khi chết | chỉ theo dõi nhân vật đầu tiên – cần CharacterAdded |
| Thanh máu tràn ra ngoài | đặt Mau ngoài Nen, hoặc dùng Offset thay vì Scale |
| Health đặt 200 nhưng chỉ được 100 | đặt Health trước MaxHealth |
Lỗi attempt to index nil ở vùng độc | nhân vật chưa xuất hiện – kiểm tra goc |
SetCoreGuiEnabled(Enum.CoreGuiType.Health, false)Color3:Lerp pha màu; .Magnitude đo khoảng cách