您的位置:首页 > 编程语言 > Go语言

Godot教程中文版-脚本2(Scripting2)

2014-03-09 10:28 411 查看
Scripting 继续上一讲 https://github.com/okamstudio/godot/wiki/tutorial_scripting_2

Processing 处理

Godot的各个动作事件会通过回调或者虚拟函数被激发,所以没有必要在运行时写检测触发的代码。此外,更多可以做的是动画编辑器。

但是,使用脚本在每一帧中进行处理仍然是一种很常见的情况。通常有两种情况的处理:空闲处理和固定处理。

当使用Node.set_process() 设置后,空闲处理会被激活。一旦被激活,Node._process()就会在每一帧回调。

例子:

func _ready():
set_process(true)

func _process(delta):
[dosomething..]

delta参数描述了从上一次调用Node._process()到这一次所用的时间(浮点数float类型,以秒为单位)。固定处理也是相似的,但是仅仅需要和物理引擎同步。

一个简单的测试方法是:在一个场景中创建一个标签节点,和以下的脚本:

extends Label

var accum=0

func _ready():
set_process(true)

func _process(delta):
accum+=delta
set_text(str(accum))

这个标签就会显示每秒钟增加的计数。

Groups 组

节点可以添加到组(按照每个节点的需要添加)。在管理大的场景的时候,这是一个简单但是有用的功能。有两个方法可以做这件事情,一是通过UI界面的组按钮Groups Button,可以看下面的图:



一个有用的例子就是绑定敌人的场景scene,如下:

func _ready():
add_to_group("enemies")

这样,如果玩家潜入了秘密基地,被发现了,所有的敌人就会被警报通知到,通过使用SceneMainLoop.call_group():

func _on_discovered():

get_scene().call_group(0,"guards","player_was_discovered")

上面的函数在组“guards”的所有成员上回调了方法player_was_discovered。很明显,通过调用SceneMainLoop.get_nodes_in_group()获取“guards”的节点列表是可能的:

var guards = get_scene().get_nodes_in_group("guards")

后面会有更多和SceneMainLoop相关的东西。

Notifications

Godot有一个通知的系统,但是它通常不需要在脚本中使用。因为它们很多都是低级的虚拟函数提供的接口。了解它们什么时候出现就可以了,简单的在你的脚本代码中添加Object._notification()函数就可以了:

func _notification(what):
if (what==NOTIFICATION_READY):
print("This is the same as overriding _ready()...")
elif (what==NOTIFICATION_PROCESS):
var delta = get_process_time()
print("This is the same as overriding _process()...")

但是,大多数的脚本都提供了简单的可继承的函数

Overrideable Function

正如上面提到的,最好使用这些函数。节点可以提供很多有用的可继承的函数,如下面所描述的:

func _enter_scene():
pass # When the node enters the active scene, this function is called. Children nodes have not entered the active scene yet. In general, it's better to use _ready() for most cases.

func _ready():
pass # This function is called after _enter_scene, but it ensures that all children nodes have also entered the active scene, and they are all functional.

func _exit_scene():
pass # When the node exists the active scene, this function is called. Children nodes have all exited the active scene at this point.

func _process(delta):
pass # When set_process() is enabled, this is called every frame

func _fixed_process(delta):
pass # When set_fixed_process() is enabled, this is called every physics frame

func _paused():
pass #Called when game is paused, after this call, the node will not receive any more process callbacks

func _unpaused():
pass #Called when game is unpaused
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: