在Godot中设置velocity移动3D Kinematic Body报错如何解决?
Godot 3D KinematicBody 水平移动报错修复方案
核心问题点
- 方法命名冲突:自定义了
move_and_slide方法,和KinematicBody内置的物理移动原生方法重名,导致调用逻辑异常 - 速度类型错误:3D场景下的移动速度应为
Vector3类型,你定义为float类型不符合物理方法的参数要求 - 移动逻辑不符合KinematicBody设计规范:直接修改
position属性会绕开物理碰撞检测,失去了使用KinematicBody的核心价值
修正代码(保留物理碰撞检测)
extends KinematicBody var KinematicBodyWidth: int var KinematicBodyHeight: int # 改为3D向量类型存储速度 var velocity: Vector3 = Vector3.ZERO func _enter_tree(): setupVelocity() setupKinematicBody() positionLeftCenter() func _physics_process(delta): # 直接调用内置move_and_slide方法,传入速度向量即可自动处理碰撞和移动 move_and_slide(velocity) func setupVelocity(): # 仅设置x轴水平速度 velocity.x = 100.0 func setupKinematicBody(): # 此处补充你的刚体初始化逻辑 pass func positionLeftCenter(): # 此处补充你的初始位置设置逻辑 pass
无需碰撞检测的简化实现
如果你不需要物理碰撞,仅想要直接修改位置实现移动,可删除自定义的move_and_slide方法,简化逻辑如下:
extends KinematicBody var KinematicBodyWidth: int var KinematicBodyHeight: int var velocity: float = 0.0 func _enter_tree(): setupVelocity() setupKinematicBody() positionLeftCenter() func _physics_process(delta): position.x += delta * velocity func setupVelocity(): velocity = 100.0 func setupKinematicBody(): pass func positionLeftCenter(): pass
内容的提问来源于stack exchange,提问作者ABHI
相关产品推荐
相关产品推荐

