1 Star 1 Fork 0

天天编程/godot-docs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
class_@gdscript.rst 88.59 KB
一键复制 编辑 原始数据 按行查看 历史
github_url: hide

@GDScript

Built-in GDScript functions.

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

Methods

:ref:`Color<class_Color>` :ref:`Color8<class_@GDScript_method_Color8>` ( :ref:`int<class_int>` r8, :ref:`int<class_int>` g8, :ref:`int<class_int>` b8, :ref:`int<class_int>` a8=255 )
:ref:`Color<class_Color>` :ref:`ColorN<class_@GDScript_method_ColorN>` ( :ref:`String<class_String>` name, :ref:`float<class_float>` alpha=1.0 )
:ref:`float<class_float>` :ref:`abs<class_@GDScript_method_abs>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`acos<class_@GDScript_method_acos>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`asin<class_@GDScript_method_asin>` ( :ref:`float<class_float>` s )
void :ref:`assert<class_@GDScript_method_assert>` ( :ref:`bool<class_bool>` condition )
:ref:`float<class_float>` :ref:`atan<class_@GDScript_method_atan>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`atan2<class_@GDScript_method_atan2>` ( :ref:`float<class_float>` y, :ref:`float<class_float>` x )
:ref:`Variant<class_Variant>` :ref:`bytes2var<class_@GDScript_method_bytes2var>` ( :ref:`PackedByteArray<class_PackedByteArray>` bytes, :ref:`bool<class_bool>` allow_objects=false )
:ref:`Vector2<class_Vector2>` :ref:`cartesian2polar<class_@GDScript_method_cartesian2polar>` ( :ref:`float<class_float>` x, :ref:`float<class_float>` y )
:ref:`float<class_float>` :ref:`ceil<class_@GDScript_method_ceil>` ( :ref:`float<class_float>` s )
:ref:`String<class_String>` :ref:`char<class_@GDScript_method_char>` ( :ref:`int<class_int>` code )
:ref:`float<class_float>` :ref:`clamp<class_@GDScript_method_clamp>` ( :ref:`float<class_float>` value, :ref:`float<class_float>` min, :ref:`float<class_float>` max )
:ref:`Variant<class_Variant>` :ref:`convert<class_@GDScript_method_convert>` ( :ref:`Variant<class_Variant>` what, :ref:`int<class_int>` type )
:ref:`float<class_float>` :ref:`cos<class_@GDScript_method_cos>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`cosh<class_@GDScript_method_cosh>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`db2linear<class_@GDScript_method_db2linear>` ( :ref:`float<class_float>` db )
:ref:`float<class_float>` :ref:`dectime<class_@GDScript_method_dectime>` ( :ref:`float<class_float>` value, :ref:`float<class_float>` amount, :ref:`float<class_float>` step )
:ref:`float<class_float>` :ref:`deg2rad<class_@GDScript_method_deg2rad>` ( :ref:`float<class_float>` deg )
:ref:`Object<class_Object>` :ref:`dict2inst<class_@GDScript_method_dict2inst>` ( :ref:`Dictionary<class_Dictionary>` dict )
:ref:`float<class_float>` :ref:`ease<class_@GDScript_method_ease>` ( :ref:`float<class_float>` s, :ref:`float<class_float>` curve )
:ref:`float<class_float>` :ref:`exp<class_@GDScript_method_exp>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`floor<class_@GDScript_method_floor>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`fmod<class_@GDScript_method_fmod>` ( :ref:`float<class_float>` a, :ref:`float<class_float>` b )
:ref:`float<class_float>` :ref:`fposmod<class_@GDScript_method_fposmod>` ( :ref:`float<class_float>` a, :ref:`float<class_float>` b )
:ref:`FuncRef<class_FuncRef>` :ref:`funcref<class_@GDScript_method_funcref>` ( :ref:`Object<class_Object>` instance, :ref:`String<class_String>` funcname )
:ref:`Array<class_Array>` :ref:`get_stack<class_@GDScript_method_get_stack>` ( )
:ref:`int<class_int>` :ref:`hash<class_@GDScript_method_hash>` ( :ref:`Variant<class_Variant>` var )
:ref:`Dictionary<class_Dictionary>` :ref:`inst2dict<class_@GDScript_method_inst2dict>` ( :ref:`Object<class_Object>` inst )
:ref:`Object<class_Object>` :ref:`instance_from_id<class_@GDScript_method_instance_from_id>` ( :ref:`int<class_int>` instance_id )
:ref:`float<class_float>` :ref:`inverse_lerp<class_@GDScript_method_inverse_lerp>` ( :ref:`float<class_float>` from, :ref:`float<class_float>` to, :ref:`float<class_float>` weight )
:ref:`bool<class_bool>` :ref:`is_equal_approx<class_@GDScript_method_is_equal_approx>` ( :ref:`float<class_float>` a, :ref:`float<class_float>` b )
:ref:`bool<class_bool>` :ref:`is_inf<class_@GDScript_method_is_inf>` ( :ref:`float<class_float>` s )
:ref:`bool<class_bool>` :ref:`is_instance_valid<class_@GDScript_method_is_instance_valid>` ( :ref:`Object<class_Object>` instance )
:ref:`bool<class_bool>` :ref:`is_nan<class_@GDScript_method_is_nan>` ( :ref:`float<class_float>` s )
:ref:`bool<class_bool>` :ref:`is_zero_approx<class_@GDScript_method_is_zero_approx>` ( :ref:`float<class_float>` s )
:ref:`int<class_int>` :ref:`len<class_@GDScript_method_len>` ( :ref:`Variant<class_Variant>` var )
:ref:`Variant<class_Variant>` :ref:`lerp<class_@GDScript_method_lerp>` ( :ref:`Variant<class_Variant>` from, :ref:`Variant<class_Variant>` to, :ref:`float<class_float>` weight )
:ref:`float<class_float>` :ref:`lerp_angle<class_@GDScript_method_lerp_angle>` ( :ref:`float<class_float>` from, :ref:`float<class_float>` to, :ref:`float<class_float>` weight )
:ref:`float<class_float>` :ref:`linear2db<class_@GDScript_method_linear2db>` ( :ref:`float<class_float>` nrg )
:ref:`Resource<class_Resource>` :ref:`load<class_@GDScript_method_load>` ( :ref:`String<class_String>` path )
:ref:`float<class_float>` :ref:`log<class_@GDScript_method_log>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`max<class_@GDScript_method_max>` ( :ref:`float<class_float>` a, :ref:`float<class_float>` b )
:ref:`float<class_float>` :ref:`min<class_@GDScript_method_min>` ( :ref:`float<class_float>` a, :ref:`float<class_float>` b )
:ref:`float<class_float>` :ref:`move_toward<class_@GDScript_method_move_toward>` ( :ref:`float<class_float>` from, :ref:`float<class_float>` to, :ref:`float<class_float>` delta )
:ref:`int<class_int>` :ref:`nearest_po2<class_@GDScript_method_nearest_po2>` ( :ref:`int<class_int>` value )
:ref:`int<class_int>` :ref:`ord<class_@GDScript_method_ord>` ( :ref:`String<class_String>` char )
:ref:`Variant<class_Variant>` :ref:`parse_json<class_@GDScript_method_parse_json>` ( :ref:`String<class_String>` json )
:ref:`Vector2<class_Vector2>` :ref:`polar2cartesian<class_@GDScript_method_polar2cartesian>` ( :ref:`float<class_float>` r, :ref:`float<class_float>` th )
:ref:`int<class_int>` :ref:`posmod<class_@GDScript_method_posmod>` ( :ref:`int<class_int>` a, :ref:`int<class_int>` b )
:ref:`float<class_float>` :ref:`pow<class_@GDScript_method_pow>` ( :ref:`float<class_float>` base, :ref:`float<class_float>` exp )
:ref:`Resource<class_Resource>` :ref:`preload<class_@GDScript_method_preload>` ( :ref:`String<class_String>` path )
void :ref:`print<class_@GDScript_method_print>` ( ... ) vararg
void :ref:`print_debug<class_@GDScript_method_print_debug>` ( ... ) vararg
void :ref:`print_stack<class_@GDScript_method_print_stack>` ( )
void :ref:`printerr<class_@GDScript_method_printerr>` ( ... ) vararg
void :ref:`printraw<class_@GDScript_method_printraw>` ( ... ) vararg
void :ref:`prints<class_@GDScript_method_prints>` ( ... ) vararg
void :ref:`printt<class_@GDScript_method_printt>` ( ... ) vararg
void :ref:`push_error<class_@GDScript_method_push_error>` ( :ref:`String<class_String>` message )
void :ref:`push_warning<class_@GDScript_method_push_warning>` ( :ref:`String<class_String>` message )
:ref:`float<class_float>` :ref:`rad2deg<class_@GDScript_method_rad2deg>` ( :ref:`float<class_float>` rad )
:ref:`float<class_float>` :ref:`rand_range<class_@GDScript_method_rand_range>` ( :ref:`float<class_float>` from, :ref:`float<class_float>` to )
:ref:`Array<class_Array>` :ref:`rand_seed<class_@GDScript_method_rand_seed>` ( :ref:`int<class_int>` seed )
:ref:`float<class_float>` :ref:`randf<class_@GDScript_method_randf>` ( )
:ref:`int<class_int>` :ref:`randi<class_@GDScript_method_randi>` ( )
void :ref:`randomize<class_@GDScript_method_randomize>` ( )
:ref:`Array<class_Array>` :ref:`range<class_@GDScript_method_range>` ( ... ) vararg
:ref:`float<class_float>` :ref:`range_lerp<class_@GDScript_method_range_lerp>` ( :ref:`float<class_float>` value, :ref:`float<class_float>` istart, :ref:`float<class_float>` istop, :ref:`float<class_float>` ostart, :ref:`float<class_float>` ostop )
:ref:`float<class_float>` :ref:`round<class_@GDScript_method_round>` ( :ref:`float<class_float>` s )
void :ref:`seed<class_@GDScript_method_seed>` ( :ref:`int<class_int>` seed )
:ref:`float<class_float>` :ref:`sign<class_@GDScript_method_sign>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`sin<class_@GDScript_method_sin>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`sinh<class_@GDScript_method_sinh>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`smoothstep<class_@GDScript_method_smoothstep>` ( :ref:`float<class_float>` from, :ref:`float<class_float>` to, :ref:`float<class_float>` weight )
:ref:`float<class_float>` :ref:`sqrt<class_@GDScript_method_sqrt>` ( :ref:`float<class_float>` s )
:ref:`int<class_int>` :ref:`step_decimals<class_@GDScript_method_step_decimals>` ( :ref:`float<class_float>` step )
:ref:`float<class_float>` :ref:`stepify<class_@GDScript_method_stepify>` ( :ref:`float<class_float>` s, :ref:`float<class_float>` step )
:ref:`String<class_String>` :ref:`str<class_@GDScript_method_str>` ( ... ) vararg
:ref:`Variant<class_Variant>` :ref:`str2var<class_@GDScript_method_str2var>` ( :ref:`String<class_String>` string )
:ref:`float<class_float>` :ref:`tan<class_@GDScript_method_tan>` ( :ref:`float<class_float>` s )
:ref:`float<class_float>` :ref:`tanh<class_@GDScript_method_tanh>` ( :ref:`float<class_float>` s )
:ref:`String<class_String>` :ref:`to_json<class_@GDScript_method_to_json>` ( :ref:`Variant<class_Variant>` var )
:ref:`bool<class_bool>` :ref:`type_exists<class_@GDScript_method_type_exists>` ( :ref:`String<class_String>` type )
:ref:`int<class_int>` :ref:`typeof<class_@GDScript_method_typeof>` ( :ref:`Variant<class_Variant>` what )
:ref:`String<class_String>` :ref:`validate_json<class_@GDScript_method_validate_json>` ( :ref:`String<class_String>` json )
:ref:`PackedByteArray<class_PackedByteArray>` :ref:`var2bytes<class_@GDScript_method_var2bytes>` ( :ref:`Variant<class_Variant>` var, :ref:`bool<class_bool>` full_objects=false )
:ref:`String<class_String>` :ref:`var2str<class_@GDScript_method_var2str>` ( :ref:`Variant<class_Variant>` var )
:ref:`WeakRef<class_WeakRef>` :ref:`weakref<class_@GDScript_method_weakref>` ( :ref:`Object<class_Object>` obj )
:ref:`float<class_float>` :ref:`wrapf<class_@GDScript_method_wrapf>` ( :ref:`float<class_float>` value, :ref:`float<class_float>` min, :ref:`float<class_float>` max )
:ref:`int<class_int>` :ref:`wrapi<class_@GDScript_method_wrapi>` ( :ref:`int<class_int>` value, :ref:`int<class_int>` min, :ref:`int<class_int>` max )
:ref:`GDScriptFunctionState<class_GDScriptFunctionState>` :ref:`yield<class_@GDScript_method_yield>` ( :ref:`Object<class_Object>` object=null, :ref:`String<class_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.

Method Descriptions

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

red = Color8(255, 0, 0)

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

red = ColorN("red", 1)

Supported color names are the same as the constants defined in :ref:`Color<class_Color>`.


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

# a is 1
a = abs(-1)

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

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

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

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

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.

# Imagine we always want speed to be between 0 and 20
speed = -10
assert(speed < 20) # True, the program will continue
assert(speed >= 0) # False, the program will stop
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 :ref:`atan2<class_@GDScript_method_atan2>` if you always want an exact angle.

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.

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.

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

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

a = char(65)      # a is "A"
a = char(65 + 32) # a is "a"
a = char(8364)    # a is "€"

This is the inverse of :ref:`ord<class_@GDScript_method_ord>`.


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

speed = 1000
# a is 20
a = clamp(speed, 1, 20)

speed = -10
# a is 1
a = clamp(speed, 1, 20)

Converts from a type to another in the best way possible. The type parameter uses the :ref:`Variant.Type<enum_@GlobalScope_Variant.Type>` values.

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

Returns the cosine of angle s in radians.

# Prints 1 then -1
print(cos(PI * 2))
print(cos(PI))

Returns the hyperbolic cosine of s in radians.

# Prints 1.543081
print(cosh(1))

Converts from decibels to linear energy (audio).


Returns the result of value decreased by step * amount.

# a = 59
a = dectime(60, 10, 0.1))

Returns degrees converted to radians.

# r is 3.141593
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 :ref:`pow<class_@GDScript_method_pow>`.

a = exp(2) # Approximately 7.39

Rounds s to the closest smaller integer and returns it.

# a is 2.0
a = floor(2.99)
# a is -3.0
a = floor(-2.99)

Note: This method returns a float. If you need an integer, you can use int(s) directly.


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

# Remainder is 1.5
var remainder = fmod(7, 5.5)

For the integer remainder operation, use the % operator.


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

var i = -6
while i < 5:
    prints(i, fposmod(i, 3))
    i += 1

Produces:

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

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 :ref:`FuncRef<class_FuncRef>` in a variable and call it later.

func foo():
    return("bar")

a = funcref(self, "foo")
print(a.call_func()) # Prints bar

Returns an array of dictionaries representing the current call stack.

func _ready():
    foo()

func foo():
    bar()

func bar():
    print(get_stack())

would print

[{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.

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

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

var foo = "bar"
func _ready():
    var d = inst2dict(self)
    print(d.keys())
    print(d.values())

Prints out:

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

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

var foo = "bar"
func _ready():
    var id = get_instance_id()
    var inst = instance_from_id(id)
    print(inst.foo) # Prints bar

Returns a normalized value considering the given range. This is the opposite of :ref:`lerp<class_@GDScript_method_lerp>`.

var middle = lerp(20, 30, 0.75)
# `middle` is now 27.5.
# Now, we pretend to have forgotten the original ratio and want to get it back.
var ratio = inverse_lerp(20, 30, 27.5)
# `ratio` is now 0.75.

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


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 true if s is zero or almost zero.


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.

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

Linearly interpolates between two values by a normalized value. This is the opposite of :ref:`inverse_lerp<class_@GDScript_method_inverse_lerp>`.

If the from and to arguments are of type :ref:`int<class_int>` or :ref:`float<class_float>`, the return value is a :ref:`float<class_float>`.

If both are of the same vector type (:ref:`Vector2<class_Vector2>`, :ref:`Vector3<class_Vector3>` or :ref:`Color<class_Color>`), the return value will be of the same type (lerp then calls the vector type's linear_interpolate method).

lerp(0, 4, 0.75) # Returns 3.0
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 :ref:`lerp<class_@GDScript_method_lerp>`, but interpolates correctly when the angles wrap around :ref:`TAU<class_@GDScript_constant_TAU>`.

extends Sprite
var elapsed = 0.0
func _process(delta):
    var min_angle = deg2rad(0.0)
    var max_angle = deg2rad(90.0)
    rotation = lerp_angle(min_angle, max_angle, elapsed)
    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:

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

Loads a resource from the filesystem located at path.

Note: Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing Copy Path.

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

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


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.

log(10) # Returns 2.302585

Returns the maximum of two values.

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

Returns the minimum of two values.

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

Moves from toward to by the delta value.

Use a negative delta value to move away.

move_toward(10, 5, 4) # Returns 6

Returns the nearest larger power of 2 for integer value.

nearest_po2(3) # Returns 4
nearest_po2(4) # Returns 4
nearest_po2(5) # Returns 8

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

a = ord("A") # a is 65
a = ord("a") # a is 97
a = ord("€") # a is 8364

This is the inverse of :ref:`char<class_@GDScript_method_char>`.


Parse JSON text to a Variant (use :ref:`typeof<class_@GDScript_method_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 :ref:`float<class_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:

p = parse_json('["a", "b", "c"]')
if typeof(p) == TYPE_ARRAY:
    print(p[0]) # Prints a
else:
    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 integer modulus of a/b that wraps equally in positive and negative.

var i = -6
while i < 5:
    prints(i, posmod(i, 3))
    i += 1

Produces:

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

Returns the result of x raised to the power of y.

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

# Load a scene called main located in the root of the project directory.
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.

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

  • void print_debug ( ... ) vararg

Like :ref:`print<class_@GDScript_method_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:

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.

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.

printraw("A")
printraw("B")
# 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 :ref:`print<class_@GDScript_method_print>`.


  • void prints ( ... ) vararg

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

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.

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

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

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

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

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

Converts from radians to degrees.

rad2deg(0.523599) # Returns 30

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

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

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

randi()           # Returns random integer between 0 and 2^32 - 1
randi() % 20      # Returns random integer between 0 and 19
randi() % 100     # Returns random integer between 0 and 99
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.

func _ready():
    randomize()

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

for i in range(4):
    print(i)
for i in range(2, 5):
    print(i)
for i in range(0, 6, 2):
    print(i)

Output:

0
1
2
3

2
3
4

0
2
4

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

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.

round(2.6) # Returns 3

Sets seed for the random number generator.

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

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

sign(-6) # Returns -1
sign(0)  # Returns 0
sign(6)  # Returns 1

Returns the sine of angle s in radians.

sin(0.523599) # Returns 0.5

Returns the hyperbolic sine of s.

a = log(2.0) # Returns 0.693147
sinh(a) # Returns 0.75

Returns a number smoothly interpolated between the from and to, based on the weight. Similar to :ref:`lerp<class_@GDScript_method_lerp>`, but interpolates faster at the beginning and slower at the end.

smoothstep(0, 2, 0.5) # Returns 0.15
smoothstep(0, 2, 1.0) # Returns 0.5
smoothstep(0, 2, 2.0) # Returns 1.0

Returns the square root of s.

sqrt(9) # Returns 3

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.

# n is 0
n = step_decimals(5)
# n is 4
n = step_decimals(1.0005)
# n is 9
n = step_decimals(0.000000005)

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.

stepify(100, 32) # Returns 96
stepify(3.14159, 0.01) # Returns 3.14

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

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

Converts a formatted string that was returned by :ref:`var2str<class_@GDScript_method_var2str>` to the original value.

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

Returns the tangent of angle s in radians.

tan(deg2rad(45)) # Returns 1

Returns the hyperbolic tangent of s.

a = log(2.0) # Returns 0.693147
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.

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

Returns whether the given class exists in :ref:`ClassDB<class_ClassDB>`.

type_exists("Sprite") # Returns true
type_exists("Variant") # Returns false

Returns the internal type of the given Variant object, using the :ref:`Variant.Type<enum_@GlobalScope_Variant.Type>` values.

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

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

j = to_json([1, 2, 3])
v = validate_json(j)
if not v:
    print("valid")
else:
    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 :ref:`str2var<class_@GDScript_method_str2var>`.

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

prints

{
"a": 1,
"b": 2
}

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.

# a is 0.5
a = wrapf(10.5, 0.0, 10.0)
# a is 9.5
a = wrapf(-0.5, 0.0, 10.0)
# Infinite loop between 0.0 and 0.99
f = wrapf(f + 0.1, 0.0, 1.0)
# Infinite rotation (in radians)
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 floating-point value), it is better for performance to use the :ref:`fmod<class_@GDScript_method_fmod>` method like fmod(number, n).

wrapf is more flexible than using the :ref:`fmod<class_@GDScript_method_fmod>` approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g.

# Infinite rotation (in radians)
angle = wrapf(angle + 0.1, -PI, PI)

Wraps integer value between min and max.

Usable for creating loop-alike behavior or infinite surfaces.

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

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

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.

# result is -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 :ref:`GDScriptFunctionState.resume<class_GDScriptFunctionState_method_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.

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

func _ready():
    yield(countdown(), "completed") # waiting for the countdown() function to complete
    print('Ready')

func countdown():
    yield(get_tree(), "idle_frame") # returns a GDScriptFunctionState object to _ready()
    print(3)
    yield(get_tree().create_timer(1.0), "timeout")
    print(2)
    yield(get_tree().create_timer(1.0), "timeout")
    print(1)
    yield(get_tree().create_timer(1.0), "timeout")

# prints:
# 3
# 2
# 1
# 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.

In order to yield on a function, the resulting function should also return a GDScriptFunctionState. Notice yield(get_tree(), "idle_frame") from the above example.

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ttcode-net/godot-docs.git
git@gitee.com:ttcode-net/godot-docs.git
ttcode-net
godot-docs
godot-docs
master

搜索帮助