使用摩擦限制加速度精确设置最大速度
前面的答案是正确的,即摩擦可以限制速度,但答案错过了有关设置限制的一些细节。
首先你的速度变量
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;
}