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
EasyDrop three blocks with one function.
- Write
func spawn(x)that makes a block atVector2(x, -30)and adds it. - In
_ready(), call it three times:spawn(160),spawn(320)andspawn(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
4Spawning
A Packed ScenePlace the New NodeA Spawn FunctionSpawn on a TimerRandom PositionsRandom LanesPractice on your own: Godot playground