主场景中,鼠标左键点击则出现浮动文字
浮动文字场景:
代码:
extends Node2D
@export var text :String
@export var velocity = Vector2.ZERO
@export var gravity = Vector2.ZERO
@export var mass = 100
func _ready():
var tween = create_tween()
#tween.tween_property($Label,"modulate",Color($Label.modulate.r,$Label.modulate.g,$Label.modulate.b,0),1.0)
$Label.scale = Vector2(0,0)
$Label.text = text
tween.tween_property($Label,"scale",Vector2(1.0,1.0),1.0)
tween.tween_property($Label,"scale",Vector2(0.0,0.0),1.0).set_delay(0.8)
tween.connect("finished",onTweenFinished)
func _process(delta):
velocity += gravity * mass * delta
position += velocity * delta
func onTweenFinished():
queue_free()
主场景代码:
extends Node2D
var float_text = preload("res://float.tscn")
func _input(event):
if event is InputEventMouseButton and event.is_pressed():
var ft = float_text.instantiate()
ft.text = str(randi() % 100 -50)
ft.velocity = Vector2(randf_range(-50,50),-100)
ft.gravity = Vector2(0,1.3)
ft.mass = 100
ft.modulate = Color(randf_range(0.7,1.0),randf_range(0.7,1.0),randf_range(0.7,1.0),1.0)
ft.position = event.position
add_child(ft)
在主场景中稍作修改,把子场景中注释掉的渐隐加到主场景中,效果更自然一点:
extends Node2D
var float_text = preload("res://float.tscn")
func _input(event):
if event is InputEventMouseButton and event.is_pressed():
var tween = create_tween()
var ft = float_text.instantiate()
ft.text = str(randi() % 100 -50)
ft.velocity = Vector2(randf_range(-50,50),-100)
ft.gravity = Vector2(0,1.3)
ft.mass = 100
ft.modulate = Color(randf_range(0.7,1.0),randf_range(0.7,1.0),randf_range(0.7,1.0),1.0)
ft.position = event.position
tween.tween_property(ft,"modulate",Color(ft.modulate.r,ft.modulate.g,ft.modulate.b,0.1),2.0)
add_child(ft)