使用摩擦限制加速度精确设置最大速度
前面的答案是正确的,摩擦可以限制速度,但答案错过了一些关于设置限制的细节。
首先是你的速度变量
vel = 0; //in pixels per frame. Start at 0 (or wherever you want)
你想要一个特定的最大速度(以每帧像素为单位)
maxVelocity = 100; // set the maximum speed
并且您有一个特定的最大加速度(以每帧像素为单位)2
maxAccel = 1; // The max acceleration will occur when accelerating from 0
你现在需要得到当速度达到 100 时停止加速所需的摩擦力。我们称之为未知摩擦力
friction = null; // what we need to find out
你将使用方程式
vel = vel + maxAccel; // accelerate
vel = vel * friction; // add friction
你知道friction 应该在加速后降低速度,这样它就不会超过maxVelocity。所以我们需要一个friction 的值,当应用于maxVelocity + maxAccel 时等于maxVelocity
maxVelocity = (maxVelocity + maxAccel) * friction;
现在只需重新排列方程以求解未知的friction 得到
friction = maxVelocity / (maxVelocity + maxAccel);
现在您有了 friction 的值,这将确保您的速度不会超过 maxVelocity。
为了稍微扩展它,您可能想要添加一个可以为您提供短期额外速度的提升,但您不希望该提升速度超过限制。您可以将friction 重新计算为新的maxVelocity,但这可能无法为您提供所需的踢球,因为速度曲线的顶端具有较低的加速度。
另一种方法是在保持相同摩擦力的同时提供额外的加速度,即计算所需的额外加速度。我们需要新的变量。
maxBoostVelocity = 120; // max boost velocity
boostAccel = null; // this will have to be calculated using the friction we have
使用与上述相同的逻辑,但根据新的最大速度和我们得到的已知摩擦重新排列摩擦解决方案
boostAccel = ((maxBoostVelocity / friction )- maxBoostVelocity);
我喜欢只使用额外的加速度来提升,所以我不必触及现有的加速度值。所以我只是从计算的提升中减去原始加速度,得到我想要的。
boostAccel = boostAccel - maxAccel;
所以在一些代码中
// the known limits
vel = 0; //in pixels per frame. Start at 0 (or wherever you want)
maxVelocity = 100; // set the maximum speed
maxAccel = 1; // The max acceleration will occur when accelerating from 0
maxBoostVelocity = 120; // max boost velocity
accelerate = false; // flag to indicate that we want to accelerate
boost = false; // flag to indicate we want to boost
// the unknown friction and boost accel
boostAccel = null; // this will have to be calculated using the friction we
friction = null; // what we need to find out
function applyAcceleration()
if(boost){ // is boosr flag true then add boost
vel += boostAccel ; // boost
}
if(accelerate || boost){ // is accelerate or boost flag true
vel += maxAccel; // accelerate
}
// always apply the friction after the accelerations
vel *= friction; // apply friction
}
// in the init function calculate the friction and boost acceleration
function init(){
friction = maxVelocity / (maxVelocity + maxAccel);
boostAccel = ((maxBoostVelocity / friction )- maxBoostVelocity) - maxAccel;
}