addforce 沿对角线移动得更快

addforce moving diagonally faster

我仍然是 Unity 的新手,我正在尝试制作一款自上而下的 2D 游戏,但我被沿对角线移动时移动速度更快的移动脚本卡住了。当我在“轴”vector2 上使用归一化并开始移动时,播放器会继续移动一点,然后当我停止按下任何键时突然停止移动,当我删除归一化时,运动恢复正常并且播放器停止缓慢移动非常完美,但当我沿对角线移动时它仍然更快。

这是我的代码:

{
Rigidbody2D rb;
Vector2 axis;

public float Speed = 400;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
    movement();
}

void movement()
{
    axis = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normlized * Speed;
    rb.AddForce(axis, ForceMode2D.Force);
    rb.drag = 60;

}
}

发生的情况是 GetAxis 的返回值在某些帧上被平滑了。因此,当您 normalize 向量时,它 returns 有一段时间 1 的幅度,即使您的输入实际上小于它,因为它正在平滑。

一般而不是

new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical").normalized`

始终 returns 幅度 1 也适用于您宁愿使用的较小输入 Vector2.ClampMagnitude

axis = Vector2.ClampMagnitude(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")), 1f) * Speed;

仅当矢量的总幅值 > 1 时才会钳位