Menu
CoddyTech

Drifting Rocks

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

Next come the rocks. A rock is a scene, rock.tscn, and rock.gd moves it. It drifts at its velocity, spins slowly and wraps like the ship. A rock is big, so it wraps at -30 and 670 instead of 0 and 640. That way it leaves the screen fully before it comes back.

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)))
challenge icon

Challenge

Hard
  1. In rock.gd, add _physics_process. Move by velocity * delta and add 0.5 * delta to rotation.
  2. Wrap the rock: past -30 or 670 on x, move it 700 the other way. Past -30 or 390 on y, move it 420.
  3. In main.gd, add const ROCK = preload("res://rock.tscn") and the spawn_rock(where, velocity) function. Spawn 4 rocks in _ready as shown.

Try it yourself

extends Area2D

var velocity = Vector2.ZERO

# Bursts into dust where the rock is. Call it when the rock breaks.
func burst():
	var dust = CPUParticles2D.new()
	dust.position = position
	dust.one_shot = true
	dust.explosiveness = 1.0
	dust.amount = 20
	dust.lifetime = 0.7
	dust.spread = 180.0
	dust.gravity = Vector2.ZERO
	dust.initial_velocity_min = 30.0
	dust.initial_velocity_max = 120.0 * scale.x
	dust.scale_amount_min = 2.0
	dust.scale_amount_max = 5.0
	dust.color = Color(0.75, 0.82, 0.95)
	dust.finished.connect(dust.queue_free)
	get_parent().add_child(dust)
	dust.emitting = true
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