我一直在互联网上寻找帮助将我的角色的速度设置为最大值 - 基本上,它的水平速度设置了一个上限。到目前为止我发现的最好的事情是:
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y);
然而,这个问题的主要问题在于,这可以防止角色的实际速度超过maxSpeed所设置的任何值(假设为4),这意味着,如果它被一个移动物体击中,它将推动它以使其水平速度将超过4,每当运动计算完成时,它将被重置为4.我正在寻找的东西会阻止角色在其自己的过去4加速,但仍然允许它随外力移动。
我的想法是只限制你想要主动设置velocity
的位置,因为用户输入并且如果它还没有更高(由于外力)。
就像是
if(Mathf.Abs(rb.velocity.x) < maxSpeed)
{
// calculate your new velocity according to user input
float newVelX = XYZ;
// than clamp it
newVelX = Mathf.Clamp(newVelX, -maxSpeed, maxSpeed);
// and finally asign the new vel
rb.velocity = new Vector2(newVelX, rb.velocity.y);
}