GODOT游戏编程005---- Scripting(2)

Scripting (continued)
http://docs.godotengine.org/en/3.0/getting_started/step_by_step/scripting_continued.html


在godot中很多动作都是有反馈或虚拟函数触发,所以没必要每次都写代码there is no need to write code that runs all the time.。
但是在每个frame(帧?)中都需要代码被处理,有两种方式处理:空闲处理和物理处理。 idle processing and physics processing.
当代码中 Node._process() 被发现时会激活空闲处理,可以通过 Node._process() 的功能打开或关闭。
物理处理取决于每秒帧数,当换帧时被激活。

     func _process(delta):
      # Do something...
      pass

delta参数包含时间流逝。The delta parameter contains the time elapsed in seconds, as a floating point
这个参数可以用来保证物体按相同时间量而不是游戏FPS。如在移动的时候,希望移动速度相同而不以帧率为准。
通过_physics_process()进行的物理处理与上面类似,它总是在物理距离physics step之前,总在固定时间间隔默认一秒60次。你可以更改项目设置来设定间隔,Physics -> Common -> Physics Fps.。
然而,_process()函数不和物理同步,它的帧率不是常数,而是取决于硬件和游戏优化,执行于物理距离之后。
一个简单的验证方法是创建一个只有一个标签Label的场景,输入代码:

extends Label

var accum = 0

func _process(delta):
    accum += delta
    text = str(accum) # 'text' is a built-in label property.

Groups分组
节点可以加入分组,这是一个组织大型场景的有用特色。有两种方法实现,一是从界面:
这里写图片描述
二是通过代码。

Notifications通知
Overrideable functions

创建节点Creating nodes
可以用.new()新建节点。

var s
func _ready():
    s = Sprite.new() # Create a new sprite!
    add_child(s) # Add it as a child of this node.

删除节点free()

func _someaction():
    s.free() # Immediately removes the node from the scene and frees it.

当一个节点被删除,它的所有子节点也被删除。
有时我们想删除一个节点时它正被“锁定blocked”,因为它正发射信号或调用函数。这会使游戏崩溃,debugger经常发生。
安全的方法是用Node.queue_free()来在空闲时删除。

func _someaction():
    s.queue_free() # Queues the Node for deletion at the end of the current Frame.

Instancing scenes引用场景
引用场景代码分为两步,一是从硬盘加载

var scene = load("res://myscene.tscn") # Will load when the script is instanced.

在解析时预载入会更方便。

var scene = preload("res://myscene.tscn") # Will load when parsing the script.

但场景并不是节点,它被打包在 PackedScene。为了创建实际的节点, PackedScene.instance() 函数必须被调用。

var node = scene.instance()
add_child(node)

这两步,对快速引用敌人、武器什么的很有用。


上面这些,额,缺乏直观感受,下一篇继续。

猜你喜欢

转载自blog.csdn.net/weixin_42944682/article/details/81842919