Random Lanes
Part of the Game Rules section of Coddy's Godot journey. Lesson 21 of 29.
Some random picks need a whole number, like one of five lanes or a die roll.
randi_range(a, b) gives a random whole number from a to b, both included:
var roll = randi_range(1, 6) # 1, 2, 3, 4, 5 or 6The screen is 640 pixels wide, so five lanes are 128 pixels each. Multiply the lane by 128, then add 64 to reach the middle of the lane:
var lane = randi_range(0, 4)
spawn(lane * 128 + 64)That gives x = 64, 192, 320, 448 or 576, and nothing in between.
Challenge
EasyMake blocks fall in five lanes. Pick a lane with randi_range(0, 4) and spawn the block at lane * 128 + 64.
Try it yourself
extends Node2D
var block_scene = preload("res://block.tscn")
func _ready():
$SpawnTimer.timeout.connect(_on_spawn_timer_timeout)
func _on_spawn_timer_timeout():
spawn(randf_range(40, 600))
func spawn(x):
var block = block_scene.instantiate()
block.position = Vector2(x, -30)
add_child(block)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Rules
Practice on your own: Godot playground