Health Bar Overlay
IntermediateOverlayDraws a health bar above the player showing current and maximum hitpoints. Demonstrates advanced overlay rendering with shapes.
15 min read
What It Does
Draws a health bar above the player showing current and maximum hitpoints. Demonstrates advanced overlay rendering with shapes.
Source Code
java
1package com.example;
2
3import net.runelite.api.Client;
4import net.runelite.api.Player;
5import net.runelite.client.ui.overlay.Overlay;
6import net.runelite.client.ui.overlay.OverlayManager;
7import net.runelite.client.plugins.Plugin;
8import net.runelite.client.plugins.PluginDescriptor;
9import javax.inject.Inject;
10import java.awt.*;
11
12@PluginDescriptor(
13 name = "Health Bar",
14 description = "Shows health bar above player"
15)
16public class HealthBarPlugin extends Plugin {
17 @Inject
18 private Client client;
19
20 @Inject
21 private OverlayManager overlayManager;
22
23 private final Overlay overlay = new Overlay() {
24 @Override
25 public Dimension render(Graphics2D graphics) {
26 Player player = client.getLocalPlayer();
27 if (player == null) {
28 return null;
29 }
30
31 Point screenPos = player.getCanvasLocation();
32 if (screenPos == null) {
33 return null;
34 }
35
36 // Use Actor.getHealthRatio() - returns ratio (0-255)
37 int healthRatio = player.getHealthRatio();
38 int maxHP = player.getMaxHealth();
39 if (maxHP == 0) {
40 maxHP = 255; // Fallback if max HP not available
41 }
42
43 // Calculate current HP from ratio
44 int currentHP = (healthRatio * maxHP) / 255;
45 int healthPercent = (currentHP * 100) / maxHP;
46
47 // Draw background
48 graphics.setColor(new Color(0, 0, 0, 150));
49 graphics.fillRect(screenPos.x - 25, screenPos.y - 40, 50, 8);
50
51 // Draw health bar
52 int barWidth = (50 * healthPercent) / 100;
53 Color healthColor = healthPercent > 50 ? Color.GREEN :
54 healthPercent > 25 ? Color.YELLOW : Color.RED;
55 graphics.setColor(healthColor);
56 graphics.fillRect(screenPos.x - 25, screenPos.y - 40, barWidth, 8);
57
58 // Draw border
59 graphics.setColor(Color.WHITE);
60 graphics.drawRect(screenPos.x - 25, screenPos.y - 40, 50, 8);
61
62 return null;
63 }
64 };
65
66 {
67 overlay.setLayer(OverlayLayer.ABOVE_SCENE);
68 }
69
70 @Override
71 protected void startUp() {
72 overlayManager.add(overlay);
73 }
74
75 @Override
76 protected void shutDown() {
77 overlayManager.remove(overlay);
78 }
79}Code Annotations
Line 28
Get player's screen position
Line 35
Calculate health percentage
Line 38
Draw semi-transparent background
Line 42
Color code based on health level
API Classes Used
Key Concepts
- •Get player's screen position
- •Calculate health percentage
- •Draw semi-transparent background
- •Color code based on health level
Next Steps
- Learn about health ratio calculations
- Add text showing HP numbers
- Add configurable colors