Menu
CoddyTech

Random Positions

Part of the Game Rules section of Coddy's Godot journey. Lesson 20 of 29.

Blocks that always fall in one place are easy to dodge. Random numbers make each round different.

randf_range(a, b) gives a random number from a to b, with decimals. Each call gives a new one:

spawn(randf_range(40, 600))

A block is 36 pixels wide. So 40 to 600 keeps every block fully on the 640 pixel screen.

Call it inside the timer's function, each time a block spawns. A number picked once and kept in a variable stays the same all game.

challenge icon

Challenge

Easy

Make each block fall at a random x between 40 and 600, picked when the block spawns.

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(320)

func spawn(x):
	var block = block_scene.instantiate()
	block.position = Vector2(x, -30)
	add_child(block)
quiz iconTest yourself

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