godot gd代码学习(2

静态类型

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

动态类型

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

数组创建

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

循环

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

检测是否有对应函数

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

不要用错缩进

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

字符

符号 意义
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 整数,A decimal integral number. Expects an integral or real number (will be floored).
o 10进制整数,An octal integral number. Expects an integral or real number (will be floored).
x 小写字母16进制,A hexadecimal integral number with lower-case letters. Expects an integral or real number (will be floored).
X 大写字母16进制,A hexadecimal integral number with upper-case letters. Expects an integral or real number (will be floored).
f 小数,A decimal real number. Expects an integral or real number.

格式化事例

10位或以下整数

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

10位整数,补零

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

保留三位小数

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

保留长度

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

配置和值都做成动态

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

输出转义字符原符号

var health = 56
print("Remaining health: %d%%" % health)
# Output: "Remaining health: 56%"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342