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 place.

  1. In _on_spawn_timer_timeout(), replace 320 with randf_range(40, 600).
  2. Keep it inside the function, so every block gets its own x.

Press Play: blocks fall all across the screen. Then Check.

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)

All lessons in Game Rules

Practice on your own: Godot playground