godot gd代碼學(xué)習(xí)(2

靜態(tài)類型

int a; // Value uninitialized
a = 5; // This is valid
a = "Hi!"; // This is invalid
void print_value(int value) {
    printf("value is %i\n", value);
}
print_value(55); // Valid
print_value("Hello"); // Invalid

動(dòng)態(tài)類型

var a # null by default
a = 5 # Valid, 'a' becomes an integer
a = "Hi!" # Valid, 'a' changed to a string
func print_value(value):
    print(value)

print_value(55) # Valid
print_value("Hello") # Valid

指針 c++

void use_class(SomeClass *instance) {
    instance->use();
}
void do_something() {
    SomeClass *instance = new SomeClass; // Created as pointer
    use_class(instance); // Passed as pointer
    delete instance; // Otherwise it will leak memory
}

指針 java

@Override
public final void use_class(SomeClass instance) {
    instance.use();
}
public final void do_something() {
    SomeClass instance = new SomeClass(); // Created as reference
    use_class(instance); // Passed as reference
    // Garbage collector will get rid of it when not in
    // use and freeze your game randomly for a second
}

引用 GDScript

func use_class(instance); # Does not care about class type
    instance.use() # Will work with any class that has a ".use()" method.

func do_something():
    var instance = SomeClass.new() # Created as reference
    use_class(instance) # Passed as reference
    # Will be unreferenced and deleted

數(shù)組創(chuàng)建

int *array = new int[4]; // Create array
array[0] = 10; // Initialize manually
array[1] = 20; // Can't mix types
array[2] = 40;
array[3] = 60;
// Can't resize
use_array(array); // Passed as pointer
delete[] array; // Must be freed
std::vector<int> array;
array.resize(4);
array[0] = 10; // Initialize manually
array[1] = 20; // Can't mix types
array[2] = 40;
array[3] = 60;
array.resize(3); // Can be resized
use_array(array); // Passed reference or value
// Freed when stack ends
var array = [10, "hello", 40, 60] # Simple, and can mix types
array.resize(3) # Can be resized
use_array(array) # Passed as reference
# Freed when no longer in use
var array = []
array.append(4)
array.append(5)
array.pop_front()
var a = 20
if a in [10, 20, 30]:
    print("We have a winner!")

字典

var d = {"name": "John", "age": 22} # Simple syntax
print("Name: ", d["name"], " Age: ", d["age"])
d["mother"] = "Rebecca" # Addition
d["age"] = 11 # Modification
d.erase("name") # Removal
var d = {
    name = "John",
    age = 22
}
print("Name: ", d.name, " Age: ", d.age) # Used "." based indexing
d["mother"] = "Rebecca"
d.mother = "Caroline" # This would work too to create a new key

循環(huán)

const char* strings = new const char*[50];
for (int i = 0; i < 50; i++){
    printf("Value: %s\n", i, strings[i]);
}
// Even in STL:
for (std::list<std::string>::const_iterator it = strings.begin(); it != strings.end(); it++) {
    std::cout << *it << std::endl;
}
for s in strings:
    print(s)
for key in dict:
    print(key, " -> ", dict[key])
for i in range(strings.size()):
    print(strings[i])
range(n) # Will go from 0 to n-1
range(b, n) # Will go from b to n-1
range(b, n, s) # Will go from b to n-1, in steps of s
for (int i = 0; i < 10; i++) {}
for (int i = 5; i < 10; i++) {}
for (int i = 5; i < 10; i += 2) {}
for i in range(10):
    pass
for i in range(5, 10):
    pass
for i in range(5, 10, 2):
    pass
for (int i = 10; i > 0; i--) {}
for i in range(10, 0, -1):
    pass
var i = 0
while i < strings.size():
    print(strings[i])
    i += 1

自定義迭代器

class FwdIterator:
    var start, curr, end, increment
    func _init(start, stop, inc):
        self.start = start
        self.curr = start
        self.end = stop
        self.increment = inc
    func is_done():
        return (curr < end)
    func do_step():
        curr += increment
        return is_done()
    func _iter_init(arg):
        curr = start
        return is_done()
    func _iter_next(arg):
        return do_step()
    func _iter_get(arg):
        return curr
var itr = FwdIterator.new(0, 6, 2)
for i in itr:
    print(i) # Will print 0, 2, and 4

檢測(cè)是否有對(duì)應(yīng)函數(shù)

func _on_object_hit(object):
    if object.has_method("smash"):
        object.smash()

不要用錯(cuò)縮進(jìn)

#good
for i in range(10):
  print("hello")
#bad
for i in range(10):
        print("hello")
#good
effect.interpolate_property(sprite, 'transform/scale',
            sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
            Tween.TRANS_QUAD, Tween.EASE_OUT)
#bad
effect.interpolate_property(sprite, 'transform/scale',
    sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
    Tween.TRANS_QUAD, Tween.EASE_OUT)
#good
if position.x > width:
    position.x = 0
if flag:
    print("flagged")
#bad
if position.x > width: position.x = 0
if flag: print("flagged")
#good
if is_colliding():
    queue_free()
#bad
if (is_colliding()):
    queue_free()
#good
position.x = 5
position.y = mpos.y + 10
dict['key'] = 5
myarray = [4, 5, 6]
print('foo')
#bad
position.x=5
position.y = mpos.y+10
dict ['key'] = 5
myarray = [4,5,6]
print ('foo')
#never
x        = 100
y        = 100
velocity = 500

命名空間

const MyCoolNode = preload('res://my_cool_node.gd')

中斷

signal door_opened
signal score_changed

格式化字符串

# Define a format string with placeholder '%s'
var format_string = "We're waiting for %s."
# Using the '%' operator, the placeholder is replaced with the desired value
var actual_string = format_string % "Godot"
print(actual_string)
# Output: "We're waiting for Godot."
# Define a format string
var format_string = "We're waiting for {str}"
# Using the 'format' method, replace the 'str' placeholder
var actual_string = format_string.format({"str": "Godot"})
print(actual_string)
# Output: "We're waiting for Godot"
var format_string = "%s was reluctant to learn %s, but now he enjoys it."
var actual_string = format_string % ["Estragon", "GDScript"]
print(actual_string)
# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."

字符

符號(hào) 意義
s 替換字符串击胜,Simple conversion to String by the same method as implicit String conversion.
c 替換字符疼蛾,A single Unicode character. Expects an unsigned 8-bit integer (0-255) for a code point or a single-character string.
d 整數(shù),A decimal integral number. Expects an integral or real number (will be floored).
o 10進(jìn)制整數(shù)赎婚,An octal integral number. Expects an integral or real number (will be floored).
x 小寫字母16進(jìn)制,A hexadecimal integral number with lower-case letters. Expects an integral or real number (will be floored).
X 大寫字母16進(jìn)制铃芦,A hexadecimal integral number with upper-case letters. Expects an integral or real number (will be floored).
f 小數(shù)涮较,A decimal real number. Expects an integral or real number.

格式化事例

10位或以下整數(shù)

print("%10d" % 12345)
# output: "     12345"

10位整數(shù),補(bǔ)零

print("%010d" % 12345)
# output: "0000012345"

保留三位小數(shù)

print("%10.3f" % 10000.5555)
# Output: " 10000.556"

保留長(zhǎng)度

print("%-10d" % 12345678)
# Output: "12345678  "

配置和值都做成動(dòng)態(tài)

var format_string = "%*.*f"
# Pad to length of 7, round to 3 decimal places:
print(format_string % [7, 3, 8.8888])
# Output: "  8.889"
#相當(dāng)于%7.3f
print("%0*d" % [2, 3])
#output: "03"
#相當(dāng)于%02d

輸出轉(zhuǎn)義字符原符號(hào)

var health = 56
print("Remaining health: %d%%" % health)
# Output: "Remaining health: 56%"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末啤誊,一起剝皮案震驚了整個(gè)濱河市岳瞭,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蚊锹,老刑警劉巖瞳筏,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異牡昆,居然都是意外死亡姚炕,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門丢烘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)柱宦,“玉大人,你說(shuō)我怎么就攤上這事播瞳〉Э” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵赢乓,是天一觀的道長(zhǎng)忧侧。 經(jīng)常有香客問(wèn)我石窑,道長(zhǎng),這世上最難降的妖魔是什么苍柏? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任尼斧,我火速辦了婚禮,結(jié)果婚禮上试吁,老公的妹妹穿的比我還像新娘棺棵。我一直安慰自己,他們只是感情好熄捍,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布烛恤。 她就那樣靜靜地躺著,像睡著了一般余耽。 火紅的嫁衣襯著肌膚如雪缚柏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天碟贾,我揣著相機(jī)與錄音币喧,去河邊找鬼。 笑死袱耽,一個(gè)胖子當(dāng)著我的面吹牛杀餐,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播朱巨,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼史翘,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了冀续?” 一聲冷哼從身側(cè)響起琼讽,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎洪唐,沒(méi)想到半個(gè)月后钻蹬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡凭需,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年脉让,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片功炮。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡溅潜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出薪伏,到底是詐尸還是另有隱情滚澜,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布嫁怀,位于F島的核電站设捐,受9級(jí)特大地震影響借浊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜萝招,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一蚂斤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧槐沼,春花似錦曙蒸、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至兼吓,卻和暖如春臂港,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背视搏。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工审孽, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人浑娜。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓佑力,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親棚愤。 傳聞我的和親對(duì)象是個(gè)殘疾皇子搓萧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354