在 Godot 中使用 Python

Dif*_*fio 3 python godot

我知道这可能是一个小众问题,但我试图了解如何使用 Python 在 Godot 中工作。我使用的是 PythonScript 库版本 0.5,并且有以下代码:

from godot import exposed, export
from godot import *


@exposed
class Node2D(KinematicBody2D):

    speed = 50
    
    def _physics_process(self,delta):
        velocity = Vector2.ZERO
        if Input.is_action_pressed('ui_up') == True:
            velocity.y -= 1*speed
            
        if Input.is_action_pressed('ui_down') == True:
            velocity.y += 1*speed
            
        move_and_slide(velocity)
Run Code Online (Sandbox Code Playgroud)

在当前状态下,当我运行它时,它会抛出“NameError:名称'move_and_slide'未定义”,尽管move_and_slide在KinematicBody2D方法中明确列出。

预先非常感谢您的反馈,如果我可以进一步澄清这个问题,请告诉我。

Dif*_*fio 5

我确实发现了这个问题!我需要添加一个自我。在 self.move_and_slide() 前面。正确代码如下:

from godot import exposed, export
from godot import *


@exposed
class Node2D(KinematicBody2D):

    
    
    def _physics_process(self,delta):
        speed = 50
        velocity = Vector2.ZERO
        if Input.is_action_pressed('ui_up') == True:
            velocity.y -= 1*speed
        
        if Input.is_action_pressed('ui_down') == True:
            velocity.y += 1*speed
            
        self.move_and_slide(velocity)

Run Code Online (Sandbox Code Playgroud)

我还需要在物理处理函数中移动速度,目前我还不能 100% 确定为什么它没有被外部注意到。

  • 因为 python 会在函数的命名空间中搜索速度。如果将 speed 变量保留在函数 _physical_process 内部,则该变量将只能从函数内部的代码中使用,您将无法再使用 self.speed 访问它。 (2认同)