(原) Godot滚动数字效果

原创文章,请后转载,并注明出处。

简单用ScrollContainer实现滚动效果,真正要好话,估计得自己用draw_string绘制,偷个懒。

extends Node2D

## 开奖号码
@export var lotterNum :String = "917651"
## 滚动速度
@export var scrollSpeed :int = 10

@onready var number: Control = $Label
@onready var scroll_label: Label = $ScrollContainer/Label
@onready var lottery_label: Label = $Label
@onready var scroll_container: ScrollContainer = $ScrollContainer

var oldScreenValue :int = -100			# 保存原有滚动值,当没变化时,表示到底
var currentNumber :int = 0 			# 当前显示第n个值

func _ready() -> void:
	setScollLabelValue()   # 设置滚动值
	var timer = Timer.new()
	timer.wait_time = 0.01
	timer.autostart = true
	timer.timeout.connect(func():
		scroll_container.scroll_vertical += scrollSpeed
		
		# 滚动到底的处理
		if scroll_container.scroll_vertical==oldScreenValue:
			number.get_children()[currentNumber].text = lotterNum.substr(currentNumber,1)
			number.get_children()[currentNumber].visible = true		
			currentNumber+=1
			if currentNumber==6:
				timer.stop()
				scroll_container.visible = false
				return
			scroll_container.scroll_vertical=0
			setScollLabelValue()
			
		else:
			oldScreenValue=scroll_container.scroll_vertical
	)
	add_child(timer)

func setScollLabelValue() -> void:
	number.get_children()[currentNumber].visible = false # 原标签隐藏
	scroll_container.position.x  = number.get_children()[currentNumber].position.x + 150 # 滚动内容定位
	scroll_label.text = ""	
	for i in range(20):
		scroll_label.text += "\n" + str(i % 10)
	for i in range(int(lotterNum.substr(currentNumber,1))):
		scroll_label.text += "\n" + str(i % 10)

相关文章