@GDScript

    List of core built-in GDScript functions. Math functions and other utilities. Everything else is provided by objects. (Keywords: builtin, built in, global functions.)

    • PI = 3.141593 —- Constant that represents how many times the diameter of a circle fits around its perimeter. This is equivalent to .
    • TAU = 6.283185 —- The circle constant, the circumference of the unit circle in radians.
    • INF = inf —- Positive infinity. For negative infinity, use -INF.
    • NAN = nan —- “Not a Number”, an invalid value. NaN has special properties, including that it is not equal to itself. It is output by some invalid operations, such as dividing zero by zero.
    • Color8 ( int r8, g8, int b8, a8=255 )

    Returns a color constructed from integer red, green, blue, and alpha channels. Each channel should have 8 bits of information ranging from 0 to 255.

    r8 red channel

    g8 green channel

    b8 blue channel

    a8 alpha channel


    Returns a color according to the standardized name with alpha ranging from 0 to 1.

    1. red = ColorN("red", 1)

    Supported color names are the same as the constants defined in .


    Returns the absolute value of parameter s (i.e. positive value).

    1. a = abs(-1) # a is 1

    Returns the arc cosine of s in radians. Use to get the angle of cosine s.

    1. # c is 0.523599 or 30 degrees if converted with rad2deg(s)
    2. c = acos(0.866025)

    Returns the arc sine of s in radians. Use to get the angle of sine s.

    1. # s is 0.523599 or 30 degrees if converted with rad2deg(s)
    2. s = asin(0.5)

    • void assert ( bool condition, message=”” )

    Asserts that the condition is true. If the condition is false, an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of push_error for reporting errors to project developers or add-on users.

    Note: For performance reasons, the code inside is only executed in debug builds or when running the project from the editor. Don’t include code that has side effects in an assert call. Otherwise, the project will behave differently when exported in release mode.

    The optional message argument, if given, is shown in addition to the generic “Assertion failed” message. You can use this to provide additional details about why the assertion failed.

    1. # Imagine we always want speed to be between 0 and 20.
    2. var speed = -10
    3. assert(speed < 20) # True, the program will continue
    4. assert(speed >= 0) # False, the program will stop
    5. assert(speed >= 0 and speed < 20) # You can also combine the two conditional statements in one check
    6. assert(speed < 20, "speed = %f, but the speed limit is 20" % speed) # Show a message with clarifying details

    Returns the arc tangent of s in radians. Use it to get the angle from an angle’s tangent in trigonometry: atan(tan(angle)) == angle.

    The method cannot know in which quadrant the angle should fall. See if you have both y and x.

    1. a = atan(0.5) # a is 0.463648

    Returns the arc tangent of y/x in radians. Use to get the angle of tangent y/x. To compute the value, the method takes into account the sign of both arguments in order to determine the quadrant.

    Important note: The Y coordinate comes first, by convention.

    1. a = atan2(0, -1) # a is 3.141593

    Decodes a byte array back to a value. When allow_objects is true decoding objects is allowed.

    WARNING: Deserialized object can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats (remote code execution).


    Converts a 2D point expressed in the cartesian coordinate system (X and Y axis) to the polar coordinate system (a distance from the origin and an angle).


    Rounds s upward (towards positive infinity), returning the smallest whole number that is not less than s.

    1. a = ceil(1.45) # a is 2.0
    2. a = ceil(1.001) # a is 2.0

    See also , round, , and int.


    • char ( int code )

    Returns a character as a String of the given Unicode code point (which is compatible with ASCII code).

    1. a = char(65) # a is "A"
    2. a = char(65 + 32) # a is "a"
    3. a = char(8364) # a is "€"

    This is the inverse of .


    Clamps value and returns a value not less than min and not more than max.

    1. a = clamp(1000, 1, 20) # a is 20
    2. a = clamp(-10, 1, 20) # a is 1
    3. a = clamp(15, 1, 20) # a is 15

    Converts from a type to another in the best way possible. The type parameter uses the values.

    1. a = Vector2(1, 0)
    2. # Prints 1
    3. print(a.length())
    4. a = convert(a, TYPE_STRING)
    5. # Prints 6 as "(1, 0)" is 6 characters
    6. print(a.length())

    Returns the cosine of angle s in radians.

    1. a = cos(TAU) # a is 1.0
    2. a = cos(PI) # a is -1.0

    Returns the hyperbolic cosine of s in radians.

    1. print(cosh(1)) # Prints 1.543081

    Converts from decibels to linear energy (audio).


    • int decimals ( step )

    Deprecated alias for step_decimals.


    Returns the result of value decreased by step * amount.

    1. a = dectime(60, 10, 0.1)) # a is 59.0

    Converts an angle expressed in degrees to radians.

    1. r = deg2rad(180) # r is 3.141593

    Converts a dictionary (previously created with ) back to an instance. Useful for deserializing.


    Easing function, based on exponent. The curve values are: 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out. Negative values are in-out/out in.


    The natural exponential function. It raises the mathematical constant e to the power of s and returns it.

    e has an approximate value of 2.71828.

    For exponents to other bases use the method .

    1. a = exp(2) # Approximately 7.39

    Rounds s downward (towards negative infinity), returning the largest whole number that is not more than s.

    1. a = floor(2.45) # a is 2.0
    2. a = floor(2.99) # a is 2.0
    3. a = floor(-2.99) # a is -3.0

    See also ceil, , stepify, and .

    Note: This method returns a float. If you need an integer and s is a non-negative number, you can use int(s) directly.


    Returns the floating-point remainder of a/b, keeping the sign of a.

    1. r = fmod(7, 5.5) # r is 1.5

    For the integer remainder operation, use the % operator.


    Returns the floating-point modulus of a/b that wraps equally in positive and negative.

    1. for i in 7:
    2. var x = 0.5 * i - 1.5
    3. print("%4.1f %4.1f %4.1f" % [x, fmod(x, 1.5), fposmod(x, 1.5)])

    Produces:

    1. -1.5 -0.0 0.0
    2. -1.0 -1.0 0.5
    3. -0.5 -0.5 1.0
    4. 0.0 0.0 0.0
    5. 0.5 0.5 0.5
    6. 1.0 1.0 1.0
    7. 1.5 0.0 0.0

    Returns a reference to the specified function funcname in the instance node. As functions aren’t first-class objects in GDscript, use funcref to store a in a variable and call it later.

    1. func foo():
    2. return("bar")
    3. a = funcref(self, "foo")
    4. print(a.call_func()) # Prints bar

    Returns an array of dictionaries representing the current call stack.

    1. func _ready():
    2. foo()
    3. func foo():
    4. bar()
    5. func bar():
    6. print(get_stack())

    would print

    1. [{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}]

    Returns the integer hash of the variable passed.

    1. print(hash("a")) # Prints 177670

    Returns the passed instance converted to a dictionary (useful for serializing).

    1. var foo = "bar"
    2. func _ready():
    3. var d = inst2dict(self)
    4. print(d.keys())
    5. print(d.values())
    1. [@subpath, @path, foo]

    Returns the Object that corresponds to instance_id. All Objects have a unique instance ID.

    1. var foo = "bar"
    2. func _ready():
    3. var id = get_instance_id()
    4. var inst = instance_from_id(id)
    5. print(inst.foo) # Prints bar

    Returns a normalized value considering the given range. This is the opposite of .


    Returns true if a and b are approximately equal to each other.


    Returns whether s is an infinity value (either positive infinity or negative infinity).


    • is_instance_valid ( Object instance )

    Returns whether instance is a valid object (e.g. has not been deleted from memory).


    Returns whether s is a NaN (“Not a Number” or invalid) value.


    • is_zero_approx ( float s )

    Returns true if s is zero or almost zero.

    This method is faster than using with one value as zero.


    • int len ( var )

    Returns length of Variant var. Length is the character count of String, element count of Array, size of Dictionary, etc.

    Note: Generates a fatal error if Variant can not provide a length.

    1. a = [1, 2, 3, 4]
    2. len(a) # Returns 4

    Linearly interpolates between two values by a normalized value. This is the opposite of inverse_lerp.

    If the from and to arguments are of type or float, the return value is a .

    If both are of the same vector type (Vector2, or Color), the return value will be of the same type (lerp then calls the vector type’s linear_interpolate method).

    1. lerp(0, 4, 0.75) # Returns 3.0
    2. lerp(Vector2(1, 5), Vector2(3, 2), 0.5) # Returns Vector2(2, 3.5)

    Linearly interpolates between two angles (in radians) by a normalized value.

    Similar to , but interpolates correctly when the angles wrap around TAU.

    1. extends Sprite
    2. var elapsed = 0.0
    3. func _process(delta):
    4. var min_angle = deg2rad(0.0)
    5. var max_angle = deg2rad(90.0)
    6. rotation = lerp_angle(min_angle, max_angle, elapsed)
    7. elapsed += delta

    Converts from linear energy to decibels (audio). This can be used to implement volume sliders that behave as expected (since volume isn’t linear). Example:

    1. # "Slider" refers to a node that inherits Range such as HSlider or VSlider.
    2. # Its range must be configured to go from 0 to 1.
    3. # Change the bus name if you'd like to change the volume of a specific bus only.
    4. AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear2db($Slider.value))

    Loads a resource from the filesystem located at path. The resource is loaded on the method call (unless it’s referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use .

    Note: Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing “Copy Path” or by dragging the file from the FileSystem dock into the script.

    1. # Load a scene called main located in the root of the project directory and cache it in a variable.
    2. var main = load("res://main.tscn") # main will contain a PackedScene resource.

    Important: The path must be absolute, a local path will just return null.

    This method is a simplified version of ResourceLoader.load, which can be used for more advanced scenarios.


    Natural logarithm. The amount of time needed to reach a certain level of continuous growth.

    Note: This is not the same as the “log” function on most calculators, which uses a base 10 logarithm.

    1. log(10) # Returns 2.302585

    Returns the maximum of two values.

    1. max(1, 2) # Returns 2
    2. max(-3.99, -4) # Returns -3.99

    Returns the minimum of two values.

    1. min(1, 2) # Returns 1
    2. min(-3.99, -4) # Returns -4

    Moves from toward to by the delta value.

    Use a negative delta value to move away.

    1. move_toward(10, 5, 4) # Returns 6

    • nearest_po2 ( int value )

    Returns the nearest larger power of 2 for integer value.

    1. nearest_po2(3) # Returns 4
    2. nearest_po2(4) # Returns 4
    3. nearest_po2(5) # Returns 8

    Returns an integer representing the Unicode code point of the given Unicode character char.

    1. a = ord("A") # a is 65
    2. a = ord("a") # a is 97
    3. a = ord("€") # a is 8364

    This is the inverse of .


    Parse JSON text to a Variant. (Use typeof to check if the Variant’s type is what you expect.)

    Note: The JSON specification does not define integer or float types, but only a number type. Therefore, parsing a JSON text will convert all numerical values to types.

    Note: JSON objects do not preserve key order like Godot dictionaries, thus, you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements:

    1. var p = JSON.parse('["hello", "world", "!"]')
    2. if typeof(p.result) == TYPE_ARRAY:
    3. print(p.result[0]) # Prints "hello"
    4. else:
    5. push_error("Unexpected results.")

    See also JSON for an alternative way to parse JSON text.


    • polar2cartesian ( float r, th )

    Converts a 2D point expressed in the polar coordinate system (a distance from the origin r and an angle th) to the cartesian coordinate system (X and Y axis).


    Returns the integer modulus of a/b that wraps equally in positive and negative.

    1. for i in range(-3, 4):
    2. print("%2d %2d %2d" % [i, i % 3, posmod(i, 3)])

    Produces:

    1. -3 0 0
    2. -2 -2 1
    3. -1 -1 2
    4. 0 0 0
    5. 1 1 1
    6. 2 2 2
    7. 3 0 0

    Returns the result of base raised to the power of exp.

    1. pow(2, 5) # Returns 32.0

    Returns a Resource from the filesystem located at path. The resource is loaded during script parsing, i.e. is loaded with the script and effectively acts as a reference to that resource. Note that the method requires a constant path. If you want to load a resource from a dynamic/variable path, use load.

    Note: Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing “Copy Path” or by dragging the file from the FileSystem dock into the script.

    1. # Instance a scene.
    2. var diamond = preload("res://diamond.tscn").instance()

    • void print () vararg

    Converts one or more arguments of any type to string in the best way possible and prints them to the console.

    1. a = [1, 2, 3]
    2. print("a", "=", a) # Prints a=[1, 2, 3]

    Note: Consider using and push_warning to print error and warning messages instead of . This distinguishes them from print messages used for debugging purposes, while also displaying a stack trace when an error or warning is printed.


    • void print_debug () vararg

    Like print, but prints only when used in debug mode.


    • void print_stack ( )

    Prints a stack track at code location, only works when running with debugger turned on.

    Output in the console would look something like this:

    1. Frame 0 - res://test.gd:16 in function '_process'

    • void printerr () vararg

    Prints one or more arguments to strings in the best way possible to standard error line.

    1. printerr("prints to stderr")

    • void printraw () vararg

    Prints one or more arguments to strings in the best way possible to console. No newline is added at the end.

    1. printraw("A")
    2. printraw("B")
    3. # Prints AB

    Note: Due to limitations with Godot’s built-in console, this only prints to the terminal. If you need to print in the editor, use another method, such as .


    • void prints () vararg

    Prints one or more arguments to the console with a space between each argument.

    1. prints("A", "B", "C") # Prints A B C

    • void printt () vararg

    Prints one or more arguments to the console with a tab between each argument.

    1. printt("A", "B", "C") # Prints A B C

    • void push_error ( String message )

    Pushes an error message to Godot’s built-in debugger and to the OS terminal.

    1. push_error("test error") # Prints "test error" to debugger and terminal as error call

    • void push_warning ( message )

    Pushes a warning message to Godot’s built-in debugger and to the OS terminal.

    1. push_warning("test warning") # Prints "test warning" to debugger and terminal as warning call

    Converts an angle expressed in radians to degrees.

    1. rad2deg(0.523599) # Returns 30.0

    Random range, any floating point value between from and to.

    1. prints(rand_range(0, 1), rand_range(0, 1)) # Prints e.g. 0.135591 0.405263

    • rand_seed ( int seed )

    Random from seed: pass a seed, and an array with both number and new seed is returned. “Seed” here refers to the internal state of the pseudo random number generator. The internal state of the current implementation is 64 bits.


    • randf ( )

    Returns a random floating point value on the interval [0, 1].

    1. randf() # Returns e.g. 0.375671

    Returns a random unsigned 32 bit integer. Use remainder to obtain a random value in the interval [0, N - 1] (where N is smaller than 2^32).


    • void randomize ( )

    Randomizes the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time.

    1. func _ready():
    2. randomize()

    • range () vararg

    Returns an array with the given range. Range can be 1 argument N (0 to N-1), two arguments (initial, final-1) or three arguments (initial, final-1, increment).

    1. print(range(4))
    2. print(range(2, 5))
    3. print(range(0, 6, 2))

    Output:

    1. [2, 3, 4]
    2. [0, 2, 4]

    Maps a value from range [istart, istop] to [ostart, ostop].

    1. range_lerp(75, 0, 100, -1, 1) # Returns 0.5

    Rounds s to the nearest whole number, with halfway cases rounded away from zero.

    1. a = round(2.49) # a is 2.0
    2. a = round(2.5) # a is 3.0
    3. a = round(2.51) # a is 3.0

    See also floor, , stepify, and .


    • void seed ( int seed )

    Sets seed for the random number generator.

    1. my_seed = "Godot Rocks"

    Returns the sign of s: -1 or 1. Returns 0 if s is 0.

    1. sign(-6) # Returns -1
    2. sign(0) # Returns 0
    3. sign(6) # Returns 1

    Returns the sine of angle s in radians.

    1. sin(0.523599) # Returns 0.5

    Returns the hyperbolic sine of s.

    1. a = log(2.0) # Returns 0.693147
    2. sinh(a) # Returns 0.75

    Returns a number smoothly interpolated between the from and to, based on the weight. Similar to , but interpolates faster at the beginning and slower at the end.

    1. smoothstep(0, 2, -5.0) # Returns 0.0
    2. smoothstep(0, 2, 0.5) # Returns 0.15625
    3. smoothstep(0, 2, 1.0) # Returns 0.5
    4. smoothstep(0, 2, 2.0) # Returns 1.0

    Returns the square root of s, where s is a non-negative number.

    1. sqrt(9) # Returns 3

    If you need negative inputs, use System.Numerics.Complex in C#.


    • int step_decimals ( step )

    Returns the position of the first non-zero digit, after the decimal point. Note that the maximum return value is 10, which is a design decision in the implementation.

    1. n = step_decimals(5) # n is 0
    2. n = step_decimals(1.0005) # n is 4
    3. n = step_decimals(0.000000005) # n is 9

    Snaps float value s to a given step. This can also be used to round a floating point number to an arbitrary number of decimals.

    1. stepify(100, 32) # Returns 96.0
    2. stepify(3.14159, 0.01) # Returns 3.14

    See also , floor, , and int.


    • str () vararg

    Converts one or more arguments of any type to string in the best way possible.

    1. var a = [10, 20, 30]
    2. var b = str(a);
    3. len(a) # Returns 3
    4. len(b) # Returns 12

    Converts a formatted string that was returned by var2str to the original value.

    1. a = '{ "a": 1, "b": 2 }'
    2. b = str2var(a)
    3. print(b["a"]) # Prints 1

    Returns the tangent of angle s in radians.

    1. tan(deg2rad(45)) # Returns 1

    Returns the hyperbolic tangent of s.

    1. a = log(2.0) # a is 0.693147
    2. b = tanh(a) # b is 0.6

    Converts a var to JSON text and return the result. Useful for serializing data to store or send over the network.

    1. # Both numbers below are integers.
    2. a = { "a": 1, "b": 2 }
    3. b = to_json(a)
    4. print(b) # {"a":1, "b":2}
    5. # Both numbers above are floats, even if they display without any decimal places.

    Note: The JSON specification does not define integer or float types, but only a number type. Therefore, converting a Variant to JSON text will convert all numerical values to types.

    See also JSON for an alternative way to convert a to JSON text.


    • bool type_exists ( type )

    Returns whether the given class exists in ClassDB.

    1. type_exists("Sprite") # Returns true
    2. type_exists("Variant") # Returns false

    Returns the internal type of the given Variant object, using the values.

    1. p = parse_json('["a", "b", "c"]')
    2. if typeof(p) == TYPE_ARRAY:
    3. print(p[0]) # Prints a
    4. else:
    5. print("unexpected results")

    • String validate_json ( json )

    Checks that json is valid JSON data. Returns an empty string if valid, or an error message otherwise.

    1. j = to_json([1, 2, 3])
    2. v = validate_json(j)
    3. if not v:
    4. print("Valid JSON.")
    5. else:
    6. push_error("Invalid JSON: " + v)

    Encodes a variable value to a byte array. When full_objects is true encoding objects is allowed (and can potentially include code).


    Converts a Variant var to a formatted string that can later be parsed using .

    1. a = { "a": 1, "b": 2 }
    2. print(var2str(a))

    prints

    1. {
    2. "a": 1,
    3. "b": 2
    4. }

    Returns a weak reference to an object.

    A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.


    Wraps float value between min and max.

    Usable for creating loop-alike behavior or infinite surfaces.

    1. # Infinite loop between 5.0 and 9.9
    2. value = wrapf(value + 0.1, 5.0, 10.0)
    1. # Infinite rotation (in radians)
    2. angle = wrapf(angle + 0.1, 0.0, TAU)
    1. # Infinite rotation (in radians)
    2. angle = wrapf(angle + 0.1, -PI, PI)

    Note: If min is 0, this is equivalent to fposmod, so prefer using that instead.

    wrapf is more flexible than using the approach by giving the user control over the minimum value.


    • int wrapi ( value, int min, max )

    Wraps integer value between min and max.

    Usable for creating loop-alike behavior or infinite surfaces.

    1. # Infinite loop between 5 and 9
    2. frame = wrapi(frame + 1, 5, 10)

    Note: If min is 0, this is equivalent to posmod, so prefer using that instead.

    wrapi is more flexible than using the approach by giving the user control over the minimum value.


    Stops the function execution and returns the current suspended state to the calling function.

    From the caller, call on the state to resume execution. This invalidates the state. Within the resumed function, yield() returns whatever was passed to the resume() function call.

    If passed an object and a signal, the execution is resumed when the object emits the given signal. In this case, yield() returns the argument passed to emit_signal() if the signal takes only one argument, or an array containing all the arguments passed to emit_signal() if the signal takes multiple arguments.

    You can also use yield to wait for a function to finish:

    1. func _ready():
    2. yield(countdown(), "completed") # waiting for the countdown() function to complete
    3. print('Ready')
    4. func countdown():
    5. yield(get_tree(), "idle_frame") # returns a GDScriptFunctionState object to _ready()
    6. print(3)
    7. yield(get_tree().create_timer(1.0), "timeout")
    8. print(2)
    9. yield(get_tree().create_timer(1.0), "timeout")
    10. print(1)
    11. yield(get_tree().create_timer(1.0), "timeout")
    12. # prints:
    13. # 3
    14. # 2
    15. # 1
    16. # Ready

    When yielding on a function, the completed signal will be emitted automatically when the function returns. It can, therefore, be used as the signal parameter of the yield method to resume.