spedometer.gd 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. extends Button
  2. enum SpeedUnit {
  3. METERS_PER_SECOND,
  4. KILOMETERS_PER_HOUR,
  5. MILES_PER_HOUR,
  6. }
  7. @export var speed_unit: SpeedUnit = SpeedUnit.METERS_PER_SECOND
  8. var gradient := Gradient.new()
  9. var car_body: VehicleBody3D
  10. func _ready():
  11. # The start and end points (offset 0.0 and 1.0) are already defined in a Gradient
  12. # resource on creation. Override their colors and only create one new point.
  13. gradient.set_color(0, Color(0.7, 0.9, 1.0))
  14. gradient.set_color(1, Color(1.0, 0.3, 0.1))
  15. gradient.add_point(0.2, Color(1.0, 1.0, 1.0))
  16. func _process(_delta):
  17. var speed := car_body.linear_velocity.length()
  18. if speed_unit == SpeedUnit.METERS_PER_SECOND:
  19. text = "Speed: " + ("%.1f" % speed) + " m/s"
  20. elif speed_unit == SpeedUnit.KILOMETERS_PER_HOUR:
  21. speed *= 3.6
  22. text = "Speed: " + ("%.0f" % speed) + " km/h"
  23. else: # speed_unit == SpeedUnit.MILES_PER_HOUR:
  24. speed *= 2.23694
  25. text = "Speed: " + ("%.0f" % speed) + " mph"
  26. # Change speedometer color depending on speed in m/s (regardless of unit).
  27. add_theme_color_override("font_color", gradient.sample(remap(car_body.linear_velocity.length(), 0.0, 30.0, 0.0, 1.0)))
  28. func _on_spedometer_pressed():
  29. speed_unit = ((speed_unit + 1) % SpeedUnit.size()) as SpeedUnit