Open the ‘next_preview.gd‘ script.
We start by adding constants right after the ‘extends Node2D‘ line. And then we add the ‘func update_preview()‘ function.
extends Node2D
const CELL_SIZE := 16
var shape_key: String = ""
var shapes: Dictionary = {}
var colors: Dictionary = {}
func update_preview(new_shape_key: String, new_shapes: Dictionary, new_colors: Dictionary) -> void:
shape_key = new_shape_key
shapes = new_shapes
colors = new_colors
queue_redraw()Now we need a function to show the next shape – ‘func _draw()‘.
func _draw() -> void:
# Debug frame so we can see that the node exists
var debug_rect := Rect2(Vector2.ZERO, Vector2(80, 80))
draw_rect(debug_rect, Color(0.2, 0.2, 0.2, 1.0), false, 2.0)
if shape_key == "" or not shapes.has(shape_key):
return
var blocks: Array = shapes[shape_key]
# Find bounding box of the shape
var min_x := 999
var max_x := -999
var min_y := 999
var max_y := -999
for b in blocks:
var v: Vector2i = b
if v.x < min_x:
min_x = v.x
if v.x > max_x:
max_x = v.x
if v.y < min_y:
min_y = v.y
if v.y > max_y:
max_y = v.y
var width := (max_x - min_x + 1) * CELL_SIZE
var height := (max_y - min_y + 1) * CELL_SIZE
# Center the shape in our local 80x80 area
var total_size := Vector2(width, height)
var preview_center := Vector2(40, 40) # middle of debug_rect
var offset := preview_center - total_size * 0.5
var color: Color = Color.WHITE
if colors.has(shape_key):
color = colors[shape_key] as Color
for b in blocks:
var v: Vector2i = b
var x := (v.x - min_x) * CELL_SIZE
var y := (v.y - min_y) * CELL_SIZE
var rect := Rect2(offset + Vector2(x, y), Vector2(CELL_SIZE, CELL_SIZE))
draw_rect(rect.grow(-1), color, true)This concludes the ‘next_preview.gd‘ script. Save it.
Leave a Reply