如何在Godot中为3D向量均匀分配移动阻力?
修复Godot中移动阻力与方向相关的问题
问题根源
你当前的代码对Vector3的X、Z分量独立应用阻力衰减,这会导致速度向量的长度衰减幅度随方向变化:
- 轴向移动时(如
Vector3(14.14,0,0)),仅单个分量衰减,速度大小的衰减量等于resistance * delta - 斜向移动时(如
Vector3(10,0,10),实际速度大小14.14),两个分量同时衰减相同数值,最终速度大小的衰减量是resistance * delta * √2,远大于轴向移动的衰减幅度,不符合“相同阻力下,速度大小衰减一致”的预期。
修复方案
改为基于速度向量的整体长度进行衰减,而非单独处理分量。核心思路是:先计算速度的实际大小,对大小应用衰减,再将原向量归一化后乘以新的大小,保证方向不变的同时,速度大小的衰减量一致。
代码实现
# 获取当前速度向量的实际大小 var current_speed = direction.length() if current_speed > 0: # 对速度大小应用阻力衰减 var new_speed = move_toward(current_speed, 0, resistance * delta) # 归一化原向量后乘以新速度,得到衰减后的速度向量 direction = direction.normalized() * new_speed else: # 速度为0时直接置零,避免后续计算出错 direction = Vector3.ZERO
特殊场景处理(如保留垂直速度)
如果你的游戏中,垂直方向(Y轴)的速度不受地面阻力影响(比如跳跃时的上升/下落速度),可以单独处理XZ平面的水平速度:
# 提取水平方向的速度向量 var horizontal_dir = Vector3(direction.x, 0, direction.z) var horizontal_speed = horizontal_dir.length() if horizontal_speed > 0: var new_horizontal_speed = move_toward(horizontal_speed, 0, resistance * delta) horizontal_dir = horizontal_dir.normalized() * new_horizontal_speed # 保留原垂直方向速度,替换水平分量 direction = Vector3(horizontal_dir.x, direction.y, horizontal_dir.z)
效果验证
- 原轴向速度
Vector3(14.14,0,0):衰减后速度大小为11.14,向量为Vector3(11.14,0,0) - 原斜向速度
Vector3(10,0,10)(大小14.14):衰减后速度大小为11.14,向量约为Vector3(7.88,0,7.88),符合预期的衰减效果
内容的提问来源于stack exchange,提问作者TheJalfireKnight
相关产品推荐
相关产品推荐

