Skip to reading
GDScript Programming & Godot

15. Math, vectors and random choices

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page
Code example
func run() -> Array:
    var health: float = clampf(135.0, 0.0, 100.0)
    var halfway: float = lerpf(10.0, 20.0, 0.5)
    var distance: float = Vector3.ZERO.distance_to(Vector3(3, 0, 4))
    return [health, halfway, distance, sqrt(81.0), pow(2.0, 3.0)]

Godot supplies trigonometry, powers, square roots, rounding, interpolation and vector operations directly. Use deg_to_rad/rad_to_deg when an API expects radians but your designer value is in degrees. Use is_equal_approx for floating-point comparisons.

Code example
func run() -> int:
    var generator := RandomNumberGenerator.new()
    generator.seed = 1234
    return generator.randi_range(1, 6)

A separate RandomNumberGenerator gives your puzzle its own sequence. A fixed seed repeats a test sequence. Global randi_range/randf_range and PCA’s random helpers use shared randomness. Godot initializes the global generator; do not reseed it every time you roll.

Vector3 has x/y/z, length, normalized, dot, cross, distance_to and lerp. A position and a direction are different quantities. Normalizing a direction removes its original length.

Page 23 of 378Permalink
Go to page