Godot中KinematicBody2D检测到输入但完全不移动问题求助
问题:Godot中KinematicBody2D角色无法移动
首次使用Godot引擎,玩家角色完全无法移动,但可以检测到输入。以下是编写的GDScript代码:
extends KinematicBody2D const UP = Vector2(0,-1) const GRAVITY = 20 const MAXFALLSPEED = 200 const ACCELERATION = 30 const MAXSPEED = 100 var motion = Vector2() func _ready(): pass func _physics_process(delta): motion.y += GRAVITY if motion.y > MAXFALLSPEED: motion.y = MAXFALLSPEED if Input.is_action_pressed("right"): motion.x += ACCELERATION elif Input.is_action_pressed("left"): motion.x -= ACCELERATION else: motion.x = 0
测试游戏时角色完全没有反应。
解决方法
核心问题是未调用KinematicBody2D的移动方法。KinematicBody2D需要通过move_and_slide()或move_and_collide()方法将计算好的motion向量应用到角色上,仅更新变量不会触发实际移动。
修改后的代码如下:
extends KinematicBody2D const UP = Vector2(0,-1) const GRAVITY = 20 const MAXFALLSPEED = 200 const ACCELERATION = 30 const MAXSPEED = 100 var motion = Vector2() func _ready(): pass func _physics_process(delta): motion.y += GRAVITY if motion.y > MAXFALLSPEED: motion.y = MAXFALLSPEED if Input.is_action_pressed("right"): motion.x += ACCELERATION * delta elif Input.is_action_pressed("left"): motion.x -= ACCELERATION * delta else: motion.x = 0 # 限制水平速度不超过最大值 motion.x = clamp(motion.x, -MAXSPEED, MAXSPEED) # 调用move_and_slide应用运动,同时处理碰撞 motion = move_and_slide(motion, UP)
额外说明:
- 加速度乘以
delta是为了保证移动速度不受帧率影响,让角色在不同设备上移动表现一致 clamp函数用于限制水平速度,避免超过设定的MAXSPEEDmove_and_slide会自动处理碰撞,并返回剩余的运动向量,适合平台类游戏的移动逻辑
内容的提问来源于stack exchange,提问作者charlie
相关产品推荐
相关产品推荐

