【问题标题】:Moving my 3D Kinematic Body horizontally by setting the velocity通过设置速度水平移动我的 3D Kinematic Body
【发布时间】:2021-11-25 22:40:27
【问题描述】:

我想通过设置速度来水平移动我的运动体,但我一直在这个程序上遇到一些错误。我正在使用godot软件来做到这一点。需要一只手来帮助我。下面我附上了我的代码:

extends KinematicBody

var KinematicBodyWidth: int

var KinematicBodyHeight: int

var velocity: float

func _enter_tree():

    setupVelocity()

    setupKinematicBody()

    positionLeftCenter()

func _physics_process(_delta):

    move_and_slide(delta)

func move_and_slide(delta: float)-> void:

    position.x += delta * velocity
    
func setupVelocity():

    velocity = 100.0

感谢和问候, 阿比

【问题讨论】:

    标签: godot


    【解决方案1】:

    如果您将该代码放在KinematicBody 上,则会出现以下错误:

    Parser Error: The function signature doesn't match the parent. Parent signature is: "Vector3 move_and_slide(Vector3, Vector3=default, bool, int, float, bool)".
    

    这是因为KinematicBody 定义了一个move_and_slide。不,你不能超载。 GDScript 不支持。相反,创建具有相同名称的方法被视为尝试覆盖它,当它检查参数是否匹配时会失败。 move_and_slide 方法无论如何都不是虚拟的。


    我还想提一下move_and_slide 名称中的slide 部分指的是它如何与坡道交互。也就是说,如果KinematicBody 与它认为是斜坡的表面发生碰撞,它将在其上滑动


    现在,您可以将代码直接放在_physics_process 上,如下所示:

    func _physics_process(delta):
        position.x += delta * velocity
    

    请注意,我将参数从 _delta 重命名为 delta。您将 delta 传递给您的 move_and_slide 方法,但参数名称为 _delta

    除了 - 等等 - KinematicBody中没有positionKinematicBody2D中有),如果你想改变位置你可以写下变换的原点:

    func _physics_process(delta):
        transform.origin.x += delta * velocity
    

    你需要知道是一个传送。它不会检查碰撞。使用KinematicBody 类中定义的move_and_slide(或者如果您不想要slide 部分,请使用move_and_collide)。这样,它不仅会移动KinematicBody,还会考虑碰撞。

    顺便说一句,我认为变量是速度(标量)而不是速度(矢量)。但是,我保留了你命名它的方式。


    鉴于您有未使用的 KinematicBodyWidthKinematicBodyHeight 我怀疑您不想使用 Godot 物理对象。如果是这种情况,您可以使用常规 Spatial 节点,并使用物理查询来检测碰撞。

    我有一个解释,从设置 Godot 物理的基础知识到如何使用物理查询 elsewhere。如果您想使用 Godot 物理对象但不知道如何使用,或者您不想使用它们而使用物理查询,我认为这会对您有所帮助。


    下一个错误是 setupKinematicBodypositionLeftCenter 未定义。要么定义方法,要么删除调用。我对这些无能为力。


    顺便问一下,您确定要使用_enter_tree 而不是_ready?你确定你不想用你想要的值初始化速度 (var velocity: float = 100.0),或者你可以导出它以便从检查面板 (export var velocity: float = 100.0) 轻松设置。

    您的代码可能是这样的:

    extends KinematicBody
    
    export var speed := 100.0
    
    func _physics_process(delta):
        transform.origin.x += delta * speed
    

    或者这个:

    extends KinematicBody
    
    export var velocity := Vector3(100.0, 0.0, 0.0)
    
    func _physics_process(_delta):
        move_and_slide(velocity)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多