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
Hard- In
rock.gd, addvar size = 2andsignal broken(rock). Set the scale fromsizein_ready. Emitbrokenwithselfwhen a bullet hits. - In
main.gd, makespawn_rock(where, velocity, size)set the rock'ssizeand connect itsbrokensignal. The first 4 rocks have size 2. - When a size 2 rock breaks, spawn two size 1 rocks there with
call_deferred. Their velocities are the old one turned by0.8and-0.8, times1.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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
2Project: Asteroid Shooter
Turn the ShipFire the EnginePractice on your own: Godot playground