教你实现漂浮文本效果

漂浮文本节点

创建控制脚本,实现漂浮效果,在初始创建给一个向上运动然后往下落的效果
extends Position2D
var text setget set_text,get_text
var velocity = Vector2.ZERO
var gravity = Vector2.ZERO
var mass = 100
func _process(delta):
velocity += gravity * mass * delta
position += velocity * delta
func set_text(txt):
$Label.text = str(txt)
func get_text():
return $Label.text
接下来我们需要为该节点实现缓慢消失的效果,使用Tween
补间动画,控制Position2D
节点的Visibility -> Modulate
进行控制,并且在补间动画完成后将节点清除
extends Position2D
---
date: '2022-07-31'
tags: ['godot']
draft: false
---
# ....
func _ready():
# 消失
$Tween.interpolate_proerty(self, "modulate",
Color(modulate.r, modulate.g, modulate,b, modulate.a),
Color(modulate.r, modulate.g, modulate,b, 0),
0.3, Tween.TRANS_LINEAR, Tween.EASE_OUT, 0.7
)
# 放大
$Tween.interpolate_proerty(self, "scale",
Vector2(0, 0),
Vector2(1, 1),
0.3, Tween.TRANS_LINEAR, Tween.EASE_OUT
)
# 缩小
$Tween.interpolate_proerty(self, "scale",
Vector2(1, 1),
Vector2(0.4, 0.4),
0.3, Tween.TRANS_LINEAR, Tween.EASE_OUT, 0.7
)
$Tween.start()
---
date: '2022-07-31'
tags: ['godot']
draft: false
---
# Tween所有动画完成信号
func _on_Tween_tween_all_completed():
get_tree().queue_delete(self)
主场景
创建主场景,并且创建一个按钮,当点击后新建漂浮文本
extends Node2D
var float_text = preload("res://float.tscn")
func _on_Button_pressed():
var ft = float_text.instance()
ft.position = Vector2(200, 300)
# 控制漂浮文本的数值
ft.velocity = Vector2(rand_range(-50, 50), -130)
ft.gravity = Vector2(0, 1.5)
ft.mass(200)
# 设置随机颜色
ft.modulate = Color(rand_range(0.7, 1), rand_range(0.7, 1), rand_range(0.7, 1), 1)
var num = randi()%10 - 5
ft.text = num
if num > 0:
ft.text = "+" + ft.text
add_child(ft)