Menu
CoddyTech

Split the Rocks

Part of the Projects section of Coddy's Godot journey. Lesson 16 of 33.

A big rock should split into two small ones. Give each rock a size, 2 for big and 1 for small. In rock.gd's _ready, set scale = Vector2.ONE * size * 0.5.

The rock reports that it broke with signal broken(rock) and broken.emit(self). self is the rock. spawn_rock now takes a size and connects the signal:

func _on_rock_broken(rock):
	if rock.size == 2:
		spawn_rock.call_deferred(rock.position, rock.velocity.rotated(0.8) * 1.5, 1)
		spawn_rock.call_deferred(rock.position, rock.velocity.rotated(-0.8) * 1.5, 1)

The signal arrives while Godot is checking which areas touch. Adding an area then stops the game with Can't change this state while flushing queries. call_deferred runs the call at the end of the frame, when that is safe.

challenge icon

Challenge

Hard
  1. In rock.gd, add var size = 2 and signal broken(rock). Set the scale from size in _ready. Emit broken with self when a bullet hits.
  2. In main.gd, make spawn_rock(where, velocity, size) set the rock's size and connect its broken signal. The first 4 rocks have size 2.
  3. When a size 2 rock breaks, spawn two size 1 rocks there with call_deferred. Their velocities are the old one turned by 0.8 and -0.8, times 1.5.

Try it yourself

extends Node2D

const ROCK = preload("res://rock.tscn")

func _ready():
	for i in 4:
		spawn_rock(Vector2(randf_range(0, 640), 0), Vector2(randf_range(-90, 90), randf_range(40, 90)))

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

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

All lessons in Projects

Practice on your own: Godot playground