@GDScript

Category: Core

Brief Description

Built-in GDScript functions.

Methods

ColorColor8 ( int r8, int g8, int b8, int a8=255 )
ColorColorN ( String name, float alpha=1.0 )
floatabs ( float s )
floatacos ( float s )
floatasin ( float s )
voidassert ( bool condition )
floatatan ( float s )
floatatan2 ( float y, float x )
Variantbytes2var ( PoolByteArray bytes, bool allow_objects=false )
Vector2cartesian2polar ( float x, float y )
floatceil ( float s )
Stringchar ( int ascii )
floatclamp ( float value, float min, float max )
Variantconvert ( Variant what, int type )
floatcos ( float s )
floatcosh ( float s )
floatdb2linear ( float db )
floatdecimals ( float step )
floatdectime ( float value, float amount, float step )
floatdeg2rad ( float deg )
Objectdict2inst ( Dictionary dict )
floatease ( float s, float curve )
floatexp ( float s )
floatfloor ( float s )
floatfmod ( float x, float y )
floatfposmod ( float x, float y )
FuncReffuncref ( Object instance, String funcname )
Arrayget_stack ( )
inthash ( Variant var )
Dictionaryinst2dict ( Object inst )
Objectinstance_from_id ( int instance_id )
floatinverse_lerp ( float from, float to, float weight )
boolis_inf ( float s )
boolis_instance_valid ( Object instance )
boolis_nan ( float s )
intlen ( Variant var )
Variantlerp ( Variant from, Variant to, float weight )
floatlinear2db ( float nrg )
Resourceload ( String path )
floatlog ( float s )
floatmax ( float a, float b )
floatmin ( float a, float b )
intnearest_po2 ( int value )
Variantparse_json ( String json )
Vector2polar2cartesian ( float r, float th )
floatpow ( float x, float y )
Resourcepreload ( String path )
voidprint () vararg
voidprint_debug () vararg
voidprint_stack ( )
voidprinterr () vararg
voidprintraw () vararg
voidprints () vararg
voidprintt () vararg
voidpush_error ( String message )
voidpush_warning ( String message )
floatrad2deg ( float rad )
floatrand_range ( float from, float to )
Arrayrand_seed ( int seed )
floatrandf ( )
intrandi ( )
voidrandomize ( )
Arrayrange () vararg
floatrange_lerp ( float value, float istart, float istop, float ostart, float ostop )
floatround ( float s )
voidseed ( int seed )
floatsign ( float s )
floatsin ( float s )
floatsinh ( float s )
floatsmoothstep ( float from, float to, float weight )
floatsqrt ( float s )
floatstepify ( float s, float step )
Stringstr () vararg
Variantstr2var ( String string )
floattan ( float s )
floattanh ( float s )
Stringto_json ( Variant var )
booltype_exists ( String type )
inttypeof ( Variant what )
Stringvalidate_json ( String json )
PoolByteArrayvar2bytes ( Variant var, bool full_objects=false )
Stringvar2str ( Variant var )
WeakRefweakref ( Object obj )
floatwrapf ( float value, float min, float max )
intwrapi ( int value, int min, int max )
GDScriptFunctionStateyield ( Object object=null, String signal=”” )

Constants

  • PI = 3.141593 — Constant that represents how many times the diameter of a circle fits around its perimeter.
  • TAU = 6.283185 — The circle constant, the circumference of the unit circle.
  • INF = inf — A positive infinity. (For negative infinity, use -INF).
  • NAN = nan — Macro constant that expands to an expression of type float that represents a NaN.

The NaN values are used to identify undefined or non-representable values for floating-point elements, such as the square root of negative numbers or the result of 0/0.

Description

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

Method Descriptions

Returns a 32 bit color with red, green, blue and alpha channels. Each channel has 8 bits of information ranging from 0 to 255.

r8 red channel

g8 green channel

b8 blue channel

a8 alpha channel

  1. red = Color8(255, 0, 0)

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

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

Supported color names:

“aliceblue”, “antiquewhite”, “aqua”, “aquamarine”, “azure”, “beige”, “bisque”, “black”, “blanchedalmond”, “blue”, “blueviolet”, “brown”, “burlywood”, “cadetblue”, “chartreuse”, “chocolate”, “coral”, “cornflower”, “cornsilk”, “crimson”, “cyan”, “darkblue”, “darkcyan”, “darkgoldenrod”, “darkgray”, “darkgreen”, “darkkhaki”, “darkmagenta”, “darkolivegreen”, “darkorange”, “darkorchid”, “darkred”, “darksalmon”, “darkseagreen”, “darkslateblue”, “darkslategray”, “darkturquoise”, “darkviolet”, “deeppink”, “deepskyblue”, “dimgray”, “dodgerblue”, “firebrick”, “floralwhite”, “forestgreen”, “fuchsia”, “gainsboro”, “ghostwhite”, “gold”, “goldenrod”, “gray”, “webgray”, “green”, “webgreen”, “greenyellow”, “honeydew”, “hotpink”, “indianred”, “indigo”, “ivory”, “khaki”, “lavender”, “lavenderblush”, “lawngreen”, “lemonchiffon”, “lightblue”, “lightcoral”, “lightcyan”, “lightgoldenrod”, “lightgray”, “lightgreen”, “lightpink”, “lightsalmon”, “lightseagreen”, “lightskyblue”, “lightslategray”, “lightsteelblue”, “lightyellow”, “lime”, “limegreen”, “linen”, “magenta”, “maroon”, “webmaroon”, “mediumaquamarine”, “mediumblue”, “mediumorchid”, “mediumpurple”, “mediumseagreen”, “mediumslateblue”, “mediumspringgreen”, “mediumturquoise”, “mediumvioletred”, “midnightblue”, “mintcream”, “mistyrose”, “moccasin”, “navajowhite”, “navyblue”, “oldlace”, “olive”, “olivedrab”, “orange”, “orangered”, “orchid”, “palegoldenrod”, “palegreen”, “paleturquoise”, “palevioletred”, “papayawhip”, “peachpuff”, “peru”, “pink”, “plum”, “powderblue”, “purple”, “webpurple”, “rebeccapurple”, “red”, “rosybrown”, “royalblue”, “saddlebrown”, “salmon”, “sandybrown”, “seagreen”, “seashell”, “sienna”, “silver”, “skyblue”, “slateblue”, “slategray”, “snow”, “springgreen”, “steelblue”, “tan”, “teal”, “thistle”, “tomato”, “turquoise”, “violet”, “wheat”, “white”, “whitesmoke”, “yellow”, “yellowgreen”.


Returns the absolute value of parameter s (i.e. unsigned value, works for integer and float).

  1. # a is 1
  2. a = abs(-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 )

Asserts that the condition is true . If the condition is false, an error is generated and the program is halted until you resume it. Only executes in debug builds, or when running the game from the editor. Use it for debugging purposes, to make sure a statement is true during development.

  1. # Imagine we always want speed to be between 0 and 20
  2. speed = -10
  3. assert(speed < 20) # True, the program will continue
  4. assert(speed >= 0) # False, the program will stop
  5. assert(speed >= 0 && speed < 20) # You can also combine the two conditional statements in one check

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 atan2 if you always want an exact angle.

  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.

  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, returning the smallest integral value that is not less than s.

  1. i = ceil(1.45) # i is 2
  2. i = ceil(1.001) # i is 2

Returns a character as a String of the given ASCII code.

  1. # a is 'A'
  2. a = char(65)
  3. # a is 'a'
  4. a = char(65 + 32)

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

  1. speed = 1000
  2. # a is 20
  3. a = clamp(speed, 1, 20)
  4. speed = -10
  5. # a is 1
  6. a = clamp(speed, 1, 20)

Converts from a type to another in the best way possible. The type parameter uses the enum TYPE_* in @GlobalScope.

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

Returns the cosine of angle s in radians.

  1. # prints 1 and -1
  2. print(cos(PI * 2))
  3. print(cos(PI))

Returns the hyperbolic cosine of s in radians.

  1. # prints 1.543081
  2. print(cosh(1))

Converts from decibels to linear energy (audio).


Returns the position of the first non-zero digit, after the decimal point.

  1. # n is 2
  2. n = decimals(0.035)

Returns the result of value decreased by step * amount.

  1. # a = 59
  2. a = dectime(60, 10, 0.1))

Returns degrees converted to radians.

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

Converts a previously converted instance to a dictionary, back into an instance. Useful for deserializing.


Easing function, based on exponent. 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 pow.

  1. a = exp(2) # approximately 7.39

Rounds s to the closest smaller integer and returns it.

  1. # a is 2
  2. a = floor(2.99)
  3. # a is -3
  4. a = floor(-2.99)

Returns the floating-point remainder of x/y.

  1. # remainder is 1.5
  2. var remainder = fmod(7, 5.5)

Returns the floating-point remainder of x/y that wraps equally in positive and negative.

  1. var i = -10
  2. while i < 0:
  3. prints(i, fposmod(i, 10))
  4. i += 1

Produces:

  1. -10 10
  2. -9 1
  3. -8 2
  4. -7 3
  5. -6 4
  6. -5 5
  7. -4 6
  8. -3 7
  9. -2 8
  10. -1 9

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

Prints out:

  1. [@subpath, @path, foo]
  2. [, res://test.gd, bar]

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.

  1. inverse_lerp(3, 5, 4) # returns 0.5

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


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


Returns whether s is a NaN (Not-A-Number) value.


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.

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

If both are of the same vector type (Vector2, Vector3 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)

Converts from linear energy to decibels (audio).


Loads a resource from the filesystem located at path.

Note: Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing “Copy Path”.

  1. # load a scene called main located in the root of the project directory
  2. var main = load("res://main.tscn")

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 your calculator which is 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

  • int 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

Parse JSON text to a Variant (use typeof to check if it is what you expect).

Be aware that 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 float types.

Note that 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. p = parse_json('["a", "b", "c"]')
  2. if typeof(p) == TYPE_ARRAY:
  3. print(p[0]) # prints a
  4. else:
  5. print("unexpected results")

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 result of x raised to the power of y.

  1. pow(2, 5) # returns 32

Returns a resource from the filesystem that is loaded during script parsing.

Note: Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing “Copy Path”.

  1. # load a scene called main located in the root of the project directory
  2. var main = preload("res://main.tscn")

  • void print () vararg

Converts one or more arguments to strings in the best way possible and prints them to the console.

  1. a = [1, 2, 3]
  2. print("a", "b", a) # prints ab[1, 2, 3]

  • 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

  • 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 ( String 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 from radians to degrees.

  1. rad2deg(0.523599) # returns 30

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

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.


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] (where N is smaller than 2^32 -1).

  1. randi() # returns random integer between 0 and 2^32 - 1
  2. randi() % 20 # returns random integer between 0 and 19
  3. randi() % 100 # returns random integer between 0 and 99
  4. randi() % 100 + 1 # returns random integer between 1 and 100

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

  • Array 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. for i in range(4):
  2. print(i)
  3. for i in range(2, 5):
  4. print(i)
  5. for i in range(0, 6, 2):
  6. print(i)

Output:

  1. 0
  2. 1
  3. 2
  4. 3
  5. 2
  6. 3
  7. 4
  8. 0
  9. 2
  10. 4

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

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

Returns the integral value that is nearest to s, with halfway cases rounded away from zero.

  1. round(2.6) # returns 3

  • void seed ( int seed )

Sets seed for the random number generator.

  1. my_seed = "Godot Rocks"
  2. seed(my_seed.hash())

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 lerp, but interpolates faster at the beginning and slower at the end.

  1. smoothstep(0, 2, 0.5) # returns 0.15
  2. smoothstep(0, 2, 1.0) # returns 0.5
  3. smoothstep(0, 2, 2.0) # returns 1.0

Returns the square root of s.

  1. sqrt(9) # returns 3

Snaps float value s to a given step.


Converts one or more arguments 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) # returns 0.693147
  2. tanh(a) # returns 0.6

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

  1. a = { 'a': 1, 'b': 2 }
  2. b = to_json(a)
  3. print(b) # {"a":1, "b":2}

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 TYPE_* enum in @GlobalScope.

  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")

Checks that json is valid JSON data. Returns empty string if valid. Returns error message if not valid.

  1. j = to_json([1, 2, 3])
  2. v = validate_json(j)
  3. if not v:
  4. print("valid")
  5. else:
  6. prints("invalid", 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 str2var.

  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. # a is 0.5
  2. a = wrapf(10.5, 0.0, 10.0)
  1. # a is 9.5
  2. a = wrapf(-0.5, 0.0, 10.0)
  1. # infinite loop between 0.0 and 0.99
  2. f = wrapf(f + 0.1, 0.0, 1.0)
  1. # infinite rotation (in radians)
  2. angle = wrapf(angle + 0.1, 0.0, TAU)

Note: If you just want to wrap between 0.0 and n (where n is a positive float value) then it’s better for performance to use fmod method like fmod(number, n).

The usage of wrapf is more flexible than using the fmod approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g.

  1. # infinite rotation (in radians)
  2. angle = wrapf(angle + 0.1, -PI, PI)

Wraps integer value between min and max.

Usable for creating loop-alike behavior or infinite surfaces.

  1. # a is 0
  2. a = wrapi(10, 0, 10)
  1. # a is 9
  2. a = wrapi(-1, 0, 10)
  1. # infinite loop between 0 and 9
  2. frame = wrapi(frame + 1, 0, 10)

Note: If you just want to wrap between 0 and n (where n is a positive integer value) then it’s better for performance to use modulo operator like number % n.

The usage of wrapi is more flexible than using the modulo approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g.

  1. # result is -2
  2. var result = wrapi(-6, -5, -1)

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

From the caller, call GDScriptFunctionState.resume 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.