如何在C#游戏中控制加速和减速

Chr*_*ris 6 c# xna

我正在建立一个驾驶游戏.视图是一个透视图,玩家的视角来自向前行驶的汽车后方.当汽车向前行驶时,它周围的所有环境都会向下移动并缩放(现在看起来相当不错),这给人的印象是汽车向前移动.现在,我希望有一些逼真的驾驶控制,这样汽车可以提高速度,然后在向上箭头释放时逐渐减速.目前,当按下向上箭头时,我会调用几个精灵的所有移动功能.我正在寻找一种方法来控制它,以便在汽车缓慢等时不会经常调用这些函数.到目前为止我的代码是:

   protected void Drive()
    {
        KeyboardState keyState = Keyboard.GetState();

        if (keyState.IsKeyDown(Keys.Up))
        {
            MathHelper.Clamp(++TruckSpeed, 0, 100);
        }
        else
        {
            MathHelper.Clamp(--TruckSpeed, 0, 100);
        }

        // Instead of using the condition below, I want to use the TruckSpeed
        // variable some way to control the rate at which these are called 
        // so I can give the impression of acceleration and de-acceleration.

        if (keyState.IsKeyDown(Keys.Up))
        {
            // Lots of update calls in here
        }
   }
Run Code Online (Sandbox Code Playgroud)

我认为这应该很容易,但出于某种原因,我无法理解它.非常感谢这里的一些帮助!谢谢

ema*_*tel 4

第一个建议,不要使用++and --。让你的TruckSpeed增长速度乘以Delta Time。这意味着您的加速和减速在较慢和较快的计算机上的工作方式相同,并且与帧速率的上升无关。您还可以设置不同的增加和减少速率,以便更好地控制游戏玩法。

大致如下:

protected void Drive(GameTime gameTime) // Pass your game time
{
    KeyboardState keyState = Keyboard.GetState();
    if (keyState.IsKeyDown(Keys.Up))
    {
        TruckSpeed += AccelerationRatePerSecond * gameTime.ElapsedGameTime.TotalSeconds;
    }
    else
    {
        TruckSpeed -= DecelerationRatePerSecond * gameTime.ElapsedGameTime.TotalSeconds;
    }
    MathHelper.Clamp(TruckSpeed, 0, 100);
    ...
Run Code Online (Sandbox Code Playgroud)

另外,你可能可以替换

if (keyState.IsKeyDown(Keys.Up))
Run Code Online (Sandbox Code Playgroud)

经过

if (TruckSpeed > 0)
Run Code Online (Sandbox Code Playgroud)

不过,将相机连接到模型上并在环境中移动它可能比在卡车周围移动整个环境更简单......