label_3d_layout.gd 2.2 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
  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():
  15. $LineEdit.text = $Name.text
  16. func _process(delta):
  17. # Animate the health percentage.
  18. counter += delta
  19. set_health(50 + sin(counter * 0.5) * 50)
  20. func set_health(p_health):
  21. health = p_health
  22. $Health.text = "%d%%" % round(health)
  23. if health <= 30:
  24. # Low health alert.
  25. $Health.modulate = Color(1, 0.2, 0.1)
  26. $Health.outline_modulate = Color(0.2, 0.1, 0.0)
  27. $HealthBarForeground.modulate = Color(1, 0.2, 0.1)
  28. $HealthBarForeground.outline_modulate = Color(0.2, 0.1, 0.0)
  29. $HealthBarBackground.outline_modulate = Color(0.2, 0.1, 0.0)
  30. $HealthBarBackground.modulate = Color(0.2, 0.1, 0.0)
  31. else:
  32. $Health.modulate = Color(0.8, 1, 0.4)
  33. $Health.outline_modulate = Color(0.15, 0.2, 0.15)
  34. $HealthBarForeground.modulate = Color(0.8, 1, 0.4)
  35. $HealthBarForeground.outline_modulate = Color(0.15, 0.2, 0.15)
  36. $HealthBarBackground.outline_modulate = Color(0.15, 0.2, 0.15)
  37. $HealthBarBackground.modulate = Color(0.15, 0.2, 0.15)
  38. # Construct an health bar with `|` symbols brought very close to each other using
  39. # a custom FontVariation on the HealthBarForeground and HealthBarBackground nodes.
  40. var bar_text = ""
  41. var bar_text_bg = ""
  42. for i in round((health / 100.0) * BAR_WIDTH):
  43. bar_text += "|"
  44. for i in BAR_WIDTH:
  45. bar_text_bg += "|"
  46. $HealthBarForeground.text = str(bar_text)
  47. $HealthBarBackground.text = str(bar_text_bg)
  48. func _on_line_edit_text_changed(new_text):
  49. $Name.text = new_text
  50. # Adjust name's font size to fit within the allowed width.
  51. $Name.font_size = 32
  52. while $Name.font.get_string_size($Name.text, $Name.horizontal_alignment, -1, $Name.font_size).x > $Name.width:
  53. $Name.font_size -= 1