label_3d_layout.gd 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Layout is simulated by adjusting Label3Ds' `offset` properties.
  2. # This can be done in the inspector, or via code with the help of `Font.get_string_size()`.
  3. # For proper billboard behavior, Label3D's `offset` property
  4. # must be adjusted instead of adjusting the `position` property.
  5. extends Node3D
  6. var health := 0: set = set_health
  7. var counter := 0.0
  8. # The margin to apply between the name and health percentage (in pixels).
  9. const HEALTH_MARGIN = 25
  10. # The health bar width (in number of characters).
  11. # Higher can be more precise, at the cost of lower performance
  12. # (since more characters may need to be rendered at once).
  13. const BAR_WIDTH = 100
  14. func _ready() -> void:
  15. $LineEdit.text = $Name.text
  16. func _process(delta: float) -> void:
  17. # Animate the health percentage.
  18. counter += delta
  19. health = roundi(50 + sin(counter * 0.5) * 50)
  20. func _on_line_edit_text_changed(new_text: String) -> void:
  21. $Name.text = new_text
  22. # Adjust name's font size to fit within the allowed width.
  23. $Name.font_size = 32
  24. while $Name.font.get_string_size($Name.text, $Name.horizontal_alignment, -1, $Name.font_size).x > $Name.width:
  25. $Name.font_size -= 1
  26. func set_health(p_health: int) -> void:
  27. health = p_health
  28. $Health.text = "%d%%" % round(health)
  29. if health <= 30:
  30. # Low health alert.
  31. $Health.modulate = Color(1, 0.2, 0.1)
  32. $Health.outline_modulate = Color(0.2, 0.1, 0.0)
  33. $HealthBarForeground.modulate = Color(1, 0.2, 0.1)
  34. $HealthBarForeground.outline_modulate = Color(0.2, 0.1, 0.0)
  35. $HealthBarBackground.outline_modulate = Color(0.2, 0.1, 0.0)
  36. $HealthBarBackground.modulate = Color(0.2, 0.1, 0.0)
  37. else:
  38. $Health.modulate = Color(0.8, 1, 0.4)
  39. $Health.outline_modulate = Color(0.15, 0.2, 0.15)
  40. $HealthBarForeground.modulate = Color(0.8, 1, 0.4)
  41. $HealthBarForeground.outline_modulate = Color(0.15, 0.2, 0.15)
  42. $HealthBarBackground.outline_modulate = Color(0.15, 0.2, 0.15)
  43. $HealthBarBackground.modulate = Color(0.15, 0.2, 0.15)
  44. # Construct an health bar with `|` symbols brought very close to each other using
  45. # a custom FontVariation on the HealthBarForeground and HealthBarBackground nodes.
  46. var bar_text := ""
  47. var bar_text_bg := ""
  48. for i in roundi((health / 100.0) * BAR_WIDTH):
  49. bar_text += "|"
  50. for i in BAR_WIDTH:
  51. bar_text_bg += "|"
  52. $HealthBarForeground.text = str(bar_text)
  53. $HealthBarBackground.text = str(bar_text_bg)