Skip to reading
PCA Script Programming

17. 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
function run()
    let health = clamp(135, 0, 100)
    let halfway = lerp(10, 20, 0.5)
    let span = distance(vector3(0, 0, 0), vector3(3, 0, 4))
    return [health, halfway, span, abs(-3), round(2.6)]
end

min() and max() take separate numeric arguments, not an array to reduce. floor() rounds down;

ceil() rounds up; round() chooses the nearest integer value. clamp(value, low, high) limits a value.

lerp(start, finish, weight) interpolates numbers; 0 is the start and 1 the finish.

Code example
function run()
    randomize(1234)
    let die = random_int(1, 6)
    let amount = random_number(0, 1)
    let reply = choose(["Locked.", "Still locked."])
    let order = shuffle(["red", "green", "blue"])
    return len(order)
end

Integer random endpoints are inclusive. Use no seed for normal unpredictable play; a fixed seed makes a test sequence repeatable. The random generator is shared, so seeding it can affect other random choices. shuffle() makes a copy. choose([], fallback) is useful when a list may be empty.

distance() accepts two Vector2 values, two Vector3 values, or two numbers. It does not find a character’s position from a record reference. Read its position first. Advanced trigonometry, square roots and other native math APIs require a helper in another language; do not assume every Godot math function is a PCA builtin.

Page 24 of 357Permalink
Go to page