You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Godot中使用PythonScript 0.5时move_and_slide报错求助

问题解决:Godot PythonScript 0.5中move_and_slide未定义错误

你的代码存在两处关键问题引发报错:

  • 调用实例方法未加self前缀:在Python中,类的实例方法必须通过self.调用,move_and_slide是KinematicBody2D的实例方法,因此要写成self.move_and_slide(velocity)。
  • 访问类属性未加self:speed是类属性,在实例方法_physics_process中访问时需要用self.speed,否则会被当作未定义的局部变量,同样触发NameError。

另外,类名Node2D和继承的KinematicBody2D不一致,虽不影响运行但易造成混淆,建议改成更清晰的命名(比如Player)。

修正后的代码如下:

from godot import exposed, export
from godot import *

@exposed
class Player(KinematicBody2D):
    speed = 50
    
    def _physics_process(self, delta):
        velocity = Vector2.ZERO
        if Input.is_action_pressed('ui_up'):
            velocity.y -= self.speed
            
        if Input.is_action_pressed('ui_down'):
            velocity.y += self.speed
            
        self.move_and_slide(velocity)

补充:判断条件里== True可省略,Input.is_action_pressed本身返回布尔值,直接写if Input.is_action_pressed('ui_up'):更简洁。

内容的提问来源于stack exchange,提问作者Difio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:12:20