TableTower/ui/sparkles.gd

74 lines
2.2 KiB
GDScript3
Raw Permalink Normal View History

class_name Sparkles
extends RefCounted
## Magic sparkles (CPU particles, so they also run on mobile): a trail that
## follows the pulse up a thread, and a short burst over a result when it
## lands. Coloured with the theme's GLOW.
static var _tex: ImageTexture
## A soft four-point star, made once.
static func texture() -> ImageTexture:
if _tex == null:
var n := 16
var img := Image.create(n, n, false, Image.FORMAT_RGBA8)
var c := Vector2(n - 1, n - 1) / 2.0
for y in n:
for x in n:
var d := Vector2(x, y) - c
var glow := clampf(1.0 - d.length() / c.x, 0.0, 1.0)
var star := clampf(1.0 - minf(absf(d.x), absf(d.y)) / 1.4, 0.0, 1.0) * glow
img.set_pixel(x, y, Color(1, 1, 1, clampf(glow * glow * 0.6 + star, 0.0, 1.0)))
_tex = ImageTexture.create_from_image(img)
return _tex
static func _base(amount: int, life: float) -> CPUParticles2D:
var p := CPUParticles2D.new()
p.texture = texture()
p.amount = amount
p.lifetime = life
p.local_coords = false
p.direction = Vector2(0, -1)
p.spread = 180.0
p.gravity = Vector2(0, -18)
p.scale_amount_min = 0.35
p.scale_amount_max = 0.9
var fade := Gradient.new()
fade.set_color(0, Color(Style.GLOW, 0.95))
fade.set_color(1, Color(Style.GLOW.lightened(0.5), 0.0))
p.color_ramp = fade
var shrink := Curve.new()
shrink.add_point(Vector2(0, 1))
shrink.add_point(Vector2(1, 0.2))
p.scale_amount_curve = shrink
var mat := CanvasItemMaterial.new()
mat.blend_mode = CanvasItemMaterial.BLEND_MODE_ADD
p.material = mat
return p
## A continuous trail; move it and toggle `emitting`.
static func trail() -> CPUParticles2D:
var p := _base(36, 0.7)
p.initial_velocity_min = 4.0
p.initial_velocity_max = 22.0
p.emitting = false
return p
## A one-shot burst over `rect` (in the parent's coordinates); frees itself.
static func burst(parent: Node, rect: Rect2) -> void:
var p := _base(maxi(10, int(rect.size.x / 12.0)), 0.9)
p.one_shot = true
p.explosiveness = 0.55
p.local_coords = true
p.emission_shape = CPUParticles2D.EMISSION_SHAPE_RECTANGLE
p.emission_rect_extents = rect.size / 2.0
p.position = rect.get_center()
p.initial_velocity_min = 6.0
p.initial_velocity_max = 30.0
p.finished.connect(p.queue_free)
parent.add_child(p)
p.emitting = true