Draw health bar over enemies

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JulioYagami

I’m trying to draw a health bar over enemies, but it isn’t working and the health bar is drawn at the corner (because the health bars are children of a CanvasLayer).

I can’t place them as children of the enemies because they have rotation and it won’t work. How can I fix that?

Are the enemies physics objects that are being automatically rotated, or are you rotating them manually?

i_love_godot | 2019-12-18 16:39

Just an idea, how about using a parent node per enemy where child1 is the “actual” enemy (rotated) and child2 is the health bar.

I’m not much into 2d so I don’t know if that poses any problems here.

wombatstampede | 2019-12-18 17:01

:bust_in_silhouette: Reply From: kidscancode

Stick a Label/TextureProgress/whatever Control node in a Node2D on your player, and put this script on it:

extends Node2D

func _process(delta):
    global_rotation = 0
:bust_in_silhouette: Reply From: lvknd

Procedure:

  1. Put the health bar in a Node2D and add that as a child of the enemy
  2. Set the Node2D’s CanvasItem “Top Level” property to true (the health bar’s Top Level should be false/default)
  3. Position the Node2D at the enemy’s local origin then position its health bar wherever you want it
  4. Add a RemoteTransform2D to the enemy and position it at the enemy’s local origin
  5. Set the RemoteTransform2D’s remote path to the Node2D containing the health bar
  6. Unset the update rotation property of the RemoteTransform2D

Explanation:
Setting the Top Level property to true disconnects the Node2D/health bar from the enemy node’s transform. RemoteTransform2D reconnects it but we explicitly ignore rotation.
Note: this doesn’t require any code. In particular, we don’t need to constantly readjust the health bar’s transform in _physics_process/_process.
Note: this doesn’t require changing the root node. In particular, we don’t need to set both the enemy and health bar as children of another root node.

1 Like