Menu
CoddyTech

Spawn the Rocks

Part of the Projects section of Coddy's Godot journey. Lesson 15 of 36.

Next come the rocks. A rock is a scene, rock.tscn, with a velocity it will drift at. main.gd makes rocks with a function, so all the spawning is in one place:

func spawn_rock(where, velocity):
	var rock = ROCK.instantiate()
	rock.position = where
	rock.velocity = velocity
	add_child(rock)

In _ready, call it four times with a loop. Each rock gets a random spot on the top edge and a random velocity:

spawn_rock(Vector2(randf_range(0, 640), 0), Vector2(randf_range(-90, 90), randf_range(40, 90)))

The rocks only sit there for now. rock.gd moves them in the next lesson.

challenge icon

Challenge

Hard

Put four rocks in the game.

  1. In main.gd, add const ROCK = preload("res://rock.tscn").
  2. Write spawn_rock(where, velocity) as shown: it makes a rock, sets both, and adds it.
  3. In _ready, call it in a loop of 4 with the random line from above.

Press Play: four rocks sit along the top edge. Then Check.

Try it yourself

extends Node2D

func _ready():
	pass

All lessons in Projects

Practice on your own: Godot playground