Godot GDScript 2D横版游戏KinematicBody2D跳跃代码不生效问题
KinematicBody2D跳跃逻辑失效问题修复
问题现象
- 开发类《空洞骑士》风格的横向2D推进游戏时,玩家
KinematicBody2D节点的跳跃逻辑异常:按下绑定up动作的按键时,控制台可正常打印Worked,但角色无跳跃反应 - 重力逻辑段
velocity.y += 1000可正常运行 - 尝试将跳跃逻辑放入while循环后,连打印语句都无法触发
问题根源
原代码存在4个核心错误,直接导致跳跃失效:
get_input()函数开头直接执行velocity = Vector2(),每帧都会清空上一帧积累的垂直方向速度,跳跃冲量无法持续作用- 跳跃赋值后对整个
velocity向量执行normalized() * speed,原本设置的-1000垂直跳跃速度被归一化缩放成-200,冲量直接被砍到1/5 - 重力计算未乘以
delta,每物理帧固定加1000的垂直向下速度,直接把仅剩的-200向上速度抵消成+800向下速度,角色只会下落 - 额外用while循环包裹逻辑会直接阻塞游戏主线程,单帧内无限循环无法触发后续输入检测和帧更新,所以连打印都不会执行
原问题代码
extends KinematicBody2D export (int) var speed = 200 var velocity = Vector2() func get_input(): velocity = Vector2() if Input.is_action_pressed("right"): velocity.x += 1 if Input.is_action_pressed("left"): velocity.x -= 1 if Input.is_action_just_pressed("up"): #this bit doesnt work. velocity.y -= 1000 #this is printed though print("Worked") velocity = velocity.normalized() * speed func _physics_process(delta): get_input() velocity.y += 1000 velocity = move_and_slide(velocity)
修复方案
- 仅重置水平方向输入速度,保留垂直方向的速度积累,不要每帧清空整个速度向量
- 归一化仅处理水平移动向量,避免垂直跳跃冲量被错误缩放
- 重力值乘以
delta实现帧率无关的物理效果,数值调整到合理范围 - 增加落地检测,仅当角色站在地面时响应跳跃输入
- 移除多余的while循环,
_physics_process本身就是固定帧率的循环回调,额外套循环会阻塞线程 - 给
move_and_slide传入向上方向参数,保证落地检测接口is_on_floor()正常工作
修复后代码
extends KinematicBody2D export (int) var speed = 200 export (float) var jump_force = -450 export (float) var gravity = 1300 var velocity = Vector2.ZERO func get_input(): # 仅重置水平速度,保留垂直方向的重力/跳跃速度 velocity.x = 0 if Input.is_action_pressed("right"): velocity.x += 1 if Input.is_action_pressed("left"): velocity.x -= 1 # 仅对水平方向做归一化,避免斜向移动速度超标 velocity.x = velocity.normalized().x * speed # 仅落地时允许跳跃 if Input.is_action_just_pressed("up") and is_on_floor(): velocity.y = jump_force print("Worked") func _physics_process(delta): get_input() # 空中才施加重力,重力乘delta保证不同帧率下表现一致 if not is_on_floor(): velocity.y += gravity * delta # 传入上方向参数,支撑落地检测 velocity = move_and_slide(velocity, Vector2.UP)
内容的提问来源于stack exchange,提问作者Squirrel
相关产品推荐
相关产品推荐

