Menu
CoddyTech

A Spawn Function

Part of the Game Rules section of Coddy's Godot journey. Lesson 18 of 29.

Making a node while the game runs is called spawning. Put the spawn lines in your own function, with the x position as a parameter:

func spawn(x):
	var block = block_scene.instantiate()
	block.position = Vector2(x, -30)
	add_child(block)

Each call builds a new block. A node can be in the game only once. Calling add_child() twice with the same block is an error. So every block needs its own instantiate().

challenge icon

Challenge

Easy
  1. Write func spawn(x) that makes a block at (x, -30) and adds it.
  2. In _ready(), call it three times to drop blocks at x = 160, 320 and 480.

Try it yourself

extends Node2D

var block_scene = preload("res://block.tscn")

func _ready():
	var block = block_scene.instantiate()
	block.position = Vector2(160, -30)
	add_child(block)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Rules

Practice on your own: Godot playground