SlimePlatformer/Autoloads/transition.gd

66 lines
2.3 KiB
GDScript
Executable file

extends CanvasLayer
# Autoloaded as "Transition". Changes scenes with a 90s-style pixel dissolve:
# Transition.change_scene("res://Levels/some_level.tscn")
# Transition.reload_scene()
#
# How it works: take a screenshot of the current frame, lay it over everything,
# swap the scene underneath, then let the shader eat the screenshot away pixel
# by pixel to reveal the new scene.
# Tweak these to change the look.
const DURATION = 0.6 # seconds for the whole dissolve
const CELL_SIZE = 1.0 # 1 = single game pixels, bigger = chunkier blocks
const STEPS = 0.0 # 0 = smooth, ~12-20 = jerky retro steps
var rect := TextureRect.new()
var mat := ShaderMaterial.new()
var busy := false
func _ready() -> void:
layer = 100 # draw above every other CanvasLayer
process_mode = Node.PROCESS_MODE_ALWAYS # keep working even if the game is paused
mat.shader = preload("res://Autoloads/dissolve.gdshader")
mat.set_shader_parameter("cell_size", CELL_SIZE)
mat.set_shader_parameter("steps", STEPS)
rect.material = mat
rect.set_anchors_preset(Control.PRESET_FULL_RECT)
rect.stretch_mode = TextureRect.STRETCH_SCALE
rect.mouse_filter = Control.MOUSE_FILTER_IGNORE
rect.visible = false
add_child(rect)
func _unhandled_input(event: InputEvent) -> void:
# PROTOTYPE: press F9 to reload the level with the dissolve. Debug builds only.
if OS.is_debug_build() and event is InputEventKey and event.pressed \
and not event.echo and event.keycode == KEY_F9:
reload_scene()
# Scenes are swapped by PixelScreen, so they're drawn inside its 640x480 screen.
func change_scene(path: String) -> void:
_dissolve(func(): PixelScreen.change_scene(path))
func reload_scene() -> void:
_dissolve(func(): PixelScreen.reload_scene())
func _dissolve(swap_scene: Callable) -> void:
if busy: return
busy = true
# Snapshot the frame that's on screen right now.
var img := get_viewport().get_texture().get_image()
rect.texture = ImageTexture.create_from_image(img)
mat.set_shader_parameter("progress", 0.0)
rect.visible = true
swap_scene.call() # the new scene loads underneath the snapshot
var tween := create_tween()
tween.tween_property(mat, "shader_parameter/progress", 1.0, DURATION)
await tween.finished
rect.visible = false
rect.texture = null
busy = false