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

Drop three blocks with one function.

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

Press Play: three blocks fall side by side. Then Check.

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)

All lessons in Game Rules

Practice on your own: Godot playground