C++增量问题
假设我有一个控制某些角色移动的方法,如下所示:
void Player::moveRight( Uint32 ticks )
{
if( speedx < maxspeed ) { speedx += accel; }
x += speedx * ( ticks / 1000.f );
//collision
if( x > (float)( 800 - width ) ) { x = (float)( 800 - width ); }
}
maxspeed = 300 且 accel = 2(另外,speedx 从 0 开始)
现在这没有任何问题,直到我在方程中添加恒定的减速度/摩擦力。基本上,我有一个 1
的恒定减速度,它是从每帧的速度中减去的。因此,如果角色没有移动,它们就会逐渐停止。
问题是这样的:如果由于减速而 speedx = 299
,我的 if 语句仍然为 true,并且它继续添加 accel
,从而将速度提高到 301,过去最大速度。
对于这个问题有什么好的解决方案,这将使我能够获得任何加速度和减速度值,而不会使 if 语句出错?
Lets say I have a method which controls some character movement like the following:
void Player::moveRight( Uint32 ticks )
{
if( speedx < maxspeed ) { speedx += accel; }
x += speedx * ( ticks / 1000.f );
//collision
if( x > (float)( 800 - width ) ) { x = (float)( 800 - width ); }
}
maxspeed = 300 and accel = 2 ( also, speedx starts at 0 )
Now there is nothing wrong with this, until I add in a constant deceleration / friction into the equation. Basically, I have a constant deceleration of 1
which is subtracted from the speed each frame. This is so if the character is not moving, they come to a gradual stop.
The problem is this: If speedx = 299
because of the deceleration, my if statement is still true, and it proceeds to add accel
which brings up the speed to 301, past the maxspeed.
What would be some good solutions to this problem, which will allow me to have any acceleration and deceleration values and not trip up the if statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要反转并巩固 quasiverse 的答案,您可以使用:
这将使用非常简单的代码酌情添加或限制。
与当前大多数建议相比,其优点在于它仅执行一次加法,或执行一次比较。
To reverse and consolidate quasiverse's answer, you could use:
This will add or cap as appropriate, with very trivial code.
The advantage over most of the current suggestions is that it only performs the addition once, or performs a single comparison.
将其更改为:
在这种情况下,如果加速度导致速度超过最大值,它将简单地将速度设置为最大值。否则只会像平常一样加速。
或者,你可以这样做:
Change it to:
In this case, if acceleration causes the speed to go over the maximum it will simply set the speed to the maximum. Otherwise is will simply accelerate as normal.
Or, you could do:
最简单的解决方法可能是在调整速度后限制速度:
Simplest fix is probably to clip the speed after you adjust it:
选项 1:将
speedx
截断为maxspeed
。代码很紧凑。选项 2:在不需要时防止虚假添加。
当您处于
最大速度
时,前者会浪费额外的时间。当您低于maxspeed-accel
时,后者会浪费比较。哪个更好取决于哪种情况更有可能发生。Option 1: Truncate your
speedx
at themaxspeed
. The code is compact.Option 2: Protect against a spurious addition when you don't need it.
The former will waste an addition when you are at
maxspeed
. The latter wastes a comparison when you are belowmaxspeed-accel
. Which is better depends on which scenario is more likely.简单地夹紧 speedx 似乎就可以正常工作:
Simply clamping the speedx seems like it would work fine: