Vous êtes sur la page 1sur 6

bracket scoped

no delimeter
path delimeter is / because all OS supports it
res:// is project root
user:// special path to save game states or donwload update packs
only lowercase for all filenames as onvention for support.
load loads at the line. preload loads at compile time so can only get constant s
tring parameter.
0xFF ---> base 16 integer
"""multiline string"""
@"Node/Labe" ---> nodepath ot stringname
#typecast
int(value)
#continue to next line ---> \
rand_range(float_from, float_to) #open interval
randf() --> (0, 1)
randi() --> [0, MAX]
randomize() #reset seed
#overrideable functions
func _ready() --> called after node enters tree and all child node entered tree
func _exit_tree() --> when node and children exits tree
func _process() --> when set_process is true this is called every frame
func _fixed_process() --> when set_fixed_process(true) this is called every phys
ics frame
func _paused() --> when game is paused. node will not receive process callbacks
when this is called.
func _unpaused() --> when game is unpaused
#get Rect of screen
get_viewport_rect() --> size attribute for size
#texture
get_texture().get_size()
var res = preload("res://aa.png")
set_texture(res)
var pos = get_pos()
pos.x ... pos.y
set_pos(somePos)
------- SCENES ------------
#Instancing a scene
var scene = preload("res://someScene.scn")
var node = scene.instance()
add_child(node)
#changing a scene
get_tree().change_scene("res://pathtoscene.scn")
#last child of root is always the laoded scene
var root = get_tree().get_root()
var current_scene = root.get_child( root.get_child_count() -1 )
------- NODES -----------
get_node("nameOfNode") #get node from current node in tree.
#create and add node as child
var s = Sprite.new()
add_child(s)
#deletes node
s.free()
s.queue_free() --> #more safer way to delete node will wait when s is free from
siganlling or calling function
------- VARIABLES ---------
# variuable any type
var x #null by default
const c
export x #make var editable in property editor
onready var x = get_node("some_node") #set value only after node has called the
_ready() function
-------- FUNCTIONS -------
func some_function(args):
return x
static func helper_function(args): #no access to instance members
pass
.baseFunc(args) #call function of parent class within the child class
#call function by name
myNode.call("func_name", args)
#store function reference
var myFunc = funcref(mynode, "myFunction")
myFunc.call_func(args)

-------- ARRAYS ----------


#passed as reference for functions
var array = [12, "shit", 14]
array.resize(5)
array[-1] #access from end
array.size()
array.append(x)
array.pop_front()
array.push_back()
array.remove(index)
if x in array:
#for very large datasets >10,000 use data type specific arrays
ByteArray, IntArray, FloatArray, StringArray, Vector2Array, Vector3Array, ColorA
rray
--------- DICTIONARIES -------
var d = {"name": "john", "age": 18, 22: [1, "asd"]}
var d = {
name = "john",
age = 22
}
# adding a key to the dict
dict["newKey"] = value
dict.someKey = newValue #only work if the key name already exists
# 2d array using dictionaries
var board = {}
board(Vector(x, y)) = something
---------- DECISION -----------
if.. elif.. else

---------- LOOP ------------------


for x in aray:
for x in [2, 4, 5]
for key in dict:
print(dict[key])
for i in range([start], endExclusive, [step]):
for c in "Hello":
while(condition):
--------- OOP ----------------
No multiple inheritance
classes are stored as files
#inheritance
extends "parentClass.gd"
extends "someClass.gd".SomeInnerClass
#check if an object inherits fomr some class
const someClass = preload("someclass.gd")
if (entity extends someClass):
#constructor
func __init(args):
pass
# Get Set
-no triggered from local access
-if want to call within class. use self.var = value to call setter fucntion.
var myvar [= value] setget [setterfunc][, getterfunc]
func setterfunc(newvalue):
myvar = newvalue
func getterfunc():
return myvar
# Classes from files
var myClass = load("myClass.gd") #load class resource
var MyClass2 = preload("MyClass2.gd") #preload only once at compile time
func some_func():
var x = MyClass2.new()
x.some_method()
# Inner Class
class SomeInnerClass:
var a = 5
func some_method(args):
pass
func __init():
var c = ComeInnerClass.new()
# Export
-means that the value gets saved along with the resource/scene its attached to
-also allows value to be edited in the property editor
-must be initialized to a constant expressin or data type-hinted
export var x = 1
export(int) var number
export(int, "Warrior", "Magician") var character_job #will be enumerated as 0,1,
2, etc..
-exporting arrays make them "static" or shared between all instances
export var a = [1,2,3]
# string exports
export(String, "asdasd", "qweqwe", "pop") var some_attribute
export(String, FILE[, GLOBAL]) var f #path to file
export(String, DIR[, GLOBAL]) var f #path to a directory
export(String, FILE[, GLOBAL], "*.txt") var f #custom filter
export(String, MULTILINE) var text
# int and float exports
export(int, 20) var i #0-20
export(int, 10, 20) var i #10 - 20
export(float, 10, 20, 0.2) var f #10-20 with 0.2 steps
export(int, FLAGS) var elements = ELEMENT_FIRE | ELEMENT_WIND
export(int, FLAGS, "Fire", "Watr", "Earth", "Wind") var elements = 0 #choose fro
m available options from editor
----Fire is 1, Water is 2, Earth is 4, Wind is 8
# color exports
export(Color, RGB) var col
export(Color, RGBA) var col
---------SIGNALS -----------
signal some_signal[(optionalargs)]
func _callback_from_some_other_class(args):
pass
# connecting signal to callback function in code
func _some_func():
instance.connect("signal_name", self, "_callback"[,arg1, arg2, ...]) #op
tional forced args
#emitting custom signal
func _some_func():
emit_signal("some_signal_name"[, arg1, arg2, ...])
someInstance.emit_signal("signal_name")
# Example of geting which instance signalled the callback function (if many shar
es the same clalback function)
func _button_pressed(which):
print("Button was pressed: ",which.get_name())
func _ready():
for b in get_node("buttons").get_children():
b.connect("pressed",self,"_button_pressed",[b])
--------- COROUTINE --------
#PRACTICAL USAGE
yield( get_tree(), "idle_frame" ) # Resume execution the next fram
e
yield( get_node("AnimationPlayer"), "finished" ) # Resume execution when
animation is done playing:
#Exmpls
--result:
-hello
-my dear
-world
func myfunc():
print("hello")
yield()
print("world")
func _ready():
var y = myfunc() # Function state saved in 'y'
print("my dear")
y.resume() # 'y' resumed and is now an invalid state
#It is also possible to pass values between yield() and resume(), for example:
- result:
hello
world
cheers!
func myfunc():
print("hello")
print( yield() )
return "cheers!"
func _ready():
var y = myfunc() # Function state saved in 'y'
print( y.resume("world") ) # 'y' resumed and is now an invalid state
--------- OTHER ------------
#Duck typing. to call a certain method regardless of class
if(object.has_method("method_name")):
object.method_name()
# TOOL
-put in front of file to run code inside edcitor
tool
extends Button
func _ready():
#do something
pass
# FIXED PROCESSING
-will run code each frame
-use set_process() and _process function. delta is ms elapsed since last frame
func _ready():
set_process(true)
func _process(delta):
pass
#GROUPS
add_to_group("enemies") #add the node to the group
#call function from all members of group
func _some_func():
get_tree().call_group(0, "group_name", "some_common_method")
#get list of members of group
var members = get_tree().get_nodes_in_group("groupName")
# AUTOLOAD | SINGLETONS
var stuff = get_node("/root/singleton")
#PAUS GAME
#change pause mode from property editor to allow it to run when paused
get_tree().set_pause(true)
#Canvas Layers
Use for ordering canvasitems. + will be bove and - will be below.
-not receommended to have too much layers. Can use z-positioning for 2d controls
. set_z()
#In order to disable bluriness esp. in pixel art games.
(Menu) Scene > Project Sttings > Image Loader > Filter (OFF)