Godot 简单地使 Vector2 减速

问题描述 投票:0回答:1

对戈多来说非常陌生。我没有考虑这一点,因为我没有在其他语言中做过类似的事情,希望有一双新的眼睛 - 谢谢!

func _physics_process(delta):

if joystick_right and joystick_right.is_pressed:
    rotation = joystick_right.output.angle() + deg_to_rad(90)
    vector = Vector2(cos(rotation-deg_to_rad(90)), sin(rotation-deg_to_rad(90)))
    velocity += vector * acceleration;
    velocity = velocity.limit_length(max_speed)
    print("Velocity: ",velocity)is in
    print("Speed: ", speed)
    print("Acceleration: ",acceleration)
    
move_and_slide()

我尝试检测操纵杆何时释放,并在速度/加速度上使用

int -= 0.01
,但“速度”正在移动物体。试图降低代码的“速度”一直是一场斗争。例如,我正在伪代码中寻找类似的内容:

if (velocity > 0,0):
     velocity -= (0.01,0.01)
     #reduce velocity by 0.01 every sec

这没有意义,因为速度包含方向。我想保持方向,但在释放操纵杆后一段时间后减速到停止。

我很感激任何关于我为什么要如此愚蠢地做这件事的建议。谢谢!

android game-physics godot
1个回答
0
投票

你当然知道你可以缩放向量,并且可以使用

limit_length
(当然你可以使用
length
获得向量的长度),所以我相信你可以找到如果你真的想的话,有一种方法可以做到这一点。


但是您想要一种简单的方法。

我相信更简单的方法 - 同时与帧速率无关 - 是使用

move_toward

您希望

velocity
move_toward
零向量,通过一些“增量”(减速):

velocity = velocity.move_toward(Vector2.ZERO, deceleration * delta)

这里

deceleration * delta
move_toward
所能做的最大改变。 我假设
deceleration
具有加速度单位(每秒速度),并且 - 当然 -
delta
具有时间单位(秒),因此通过将它们相乘,我们得到了增量速度。

move_toward
不会超调。也就是说,如果
velocity
Vector2.ZERO
之间的距离大于
deceleration * delta
,您将得到
Vector2.ZERO
,而不是速度翻转到相反方向。


如果您通过其他方式改变速度,您可以通过检查

signf
产品的
dot
来检查结果是否朝相反方向变化。如果它们大致沿同一方向,则点积为正;如果它们彼此垂直,则点积为零;如果它们大致沿相反方向,则点积为负。


为了清楚起见,如果您必须自己实现

move_toward
(您不需要),那么它会是这样的:

func move_toward(from:Vector2, to:Vector2, step:float) -> Vector2:
    var difference := to - from
    var distance := difference.length()
    if is_zero_approx(distance) or distance < step:
        return to
    else:
        var direction := difference / distance
        return from + direction * step

如您所见,这里我们将使用

if
来确保我们不会超出范围。

difference
除以
distance
得到一个单位向量(假设
distance
不为零,请参见
is_zero_approx
)。

获取单位向量的另一种方法是使用

normalized
。或者我们可以使用
direction_to
distance_to
,这可能会使代码更具可读性。

© www.soinside.com 2019 - 2024. All rights reserved.