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
HardPut four rocks in the game.
- In
main.gd, addconst ROCK = preload("res://rock.tscn"). - Write
spawn_rock(where, velocity)as shown: it makes a rock, sets both, and adds it. - 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
2Project: Asteroid Shooter
Turn the ShipFire the EnginePractice on your own: Godot playground