Progression et minuteur
Un Timer qui remplit une barre, avec pause et reprise. La barre lit time_left, elle ne compte pas toute seule.
L'éditeur ci-dessus fait tourner ce projet. Changez une ligne et il se recharge.
Classes Godot utilisées
ProgressBarTimerButton
Le code
scripts/main.gd
extends Node
const DURATION: float = 4.0
var bar: ProgressBar
var countdown: Label
var timer: Timer
var running: bool = true
func _ready() -> void:
var column: VBoxContainer = _root()
var title: Label = Label.new()
title.text = 'Timer drives the bar'
title.add_theme_font_size_override('font_size', 26)
column.add_child(title)
bar = ProgressBar.new()
bar.max_value = DURATION
bar.show_percentage = false
bar.custom_minimum_size = Vector2(420, 26)
bar.add_theme_stylebox_override('background', _bar_style(Color('#2a2f3d')))
bar.add_theme_stylebox_override('fill', _bar_style(Color('#8eef97')))
column.add_child(bar)
countdown = Label.new()
countdown.add_theme_color_override('font_color', Color('#8eef97'))
column.add_child(countdown)
var toggle: Button = Button.new()
toggle.text = 'pause'
toggle.pressed.connect(func(): _toggle(toggle))
column.add_child(toggle)
timer = Timer.new()
timer.wait_time = DURATION
timer.timeout.connect(_on_timeout)
add_child(timer)
timer.start()
func _process(_delta: float) -> void:
bar.value = DURATION - timer.time_left
countdown.text = '%.1f s left' % timer.time_left
func _on_timeout() -> void:
bar.value = 0
timer.start()
func _toggle(button: Button) -> void:
running = not running
timer.paused = not running
button.text = 'resume' if not running else 'pause'
func _bar_style(color: Color) -> StyleBoxFlat:
var style: StyleBoxFlat = StyleBoxFlat.new()
style.bg_color = color
style.set_corner_radius_all(6)
return style
func _root() -> VBoxContainer:
var background: ColorRect = ColorRect.new()
background.color = Color('#12141a')
add_child(background)
background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var center: CenterContainer = CenterContainer.new()
add_child(center)
center.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var column: VBoxContainer = VBoxContainer.new()
column.add_theme_constant_override('separation', 20)
center.add_child(column)
return column