使用类实时更新的其他变量

时间:2013-12-26 16:29:27

标签: c# xna monogame

我正在使用monogame在C#中制作自上而下的汽车游戏。 (我标记了XNA,因为monogame也使用XNA。它完全相同)

游戏现在看起来像这样: This is what the car game currently looks like

虽然我对车的速度有些问题。 我在Background类中有一个变量,速度正在增加,但是我正在尝试对汽车做同样的事情,但是有一个额外的速度,所以它有一个幻想的汽车进一步移动。我把它包含在汽车的代码中:

Background b = new Background();

背景中的速度每帧增加“0.001”,并放在类的更新部分。

background.cs

public void Update(GameTime gameTime)
{
  //blahblahcode
  speed += 0.001;
  //blahblahcode
}
在oponnent.cs中的

我在代码中有这个。

public void Update(GameTime gameTime)
{
    float Timer1 = (float)gameTime.ElapsedGameTime.TotalSeconds;
    timer1_time -= Timer1;
    int speedp = (int)b.speed + 1;
    Console.WriteLine(b.speed);
    if (timer1_time <= 0)
    {
        timer1_time = 4;
        randNum = rand.Next(3);
        carDrivePos = cardefault_y;

        if (randNum == 0)
        {
            lane = p.posLeft;
        }
        else if (randNum == 1)
        {
            lane = p.posMid;
        }
        else if (randNum == 2)
        {
            lane = p.posLeft;
        }
    }
    carDrivePos += (int)b.speed + speedp;
    carPos = new Vector2(lane, carDrivePos);
}

它有点奇怪的编码,但我理解它,它的工作原理,一点点。 你可以看到我有

int speedp = (int)b.speed + 1;

我认为应该抓住每一帧的速度。但事实并非如此。它只能从我在'Background.cs'中指定的数字中获取,这是2号。所以汽车保持2速+ 1。所以速度实际上是3,所以如果背景继续移动得更快,那么汽车只保留同样的速度。

我怎样才能让它像'Background.cs'一样更新速度? 提前致谢。 (对不起,如果这很难理解)

1 个答案:

答案 0 :(得分:0)

通过查看变量类型可以浮出水面:

  • Background.speed是双重(或类似)
  • Opponent.Update方法声明speedp是一个int

在Background类中,Update方法正在更新Background.speed:

// Background sets the initial value
speed = 2d;

// The Background.Update Method updates the value
speed += 0.001;
// speed now equals 2.001;

但是,在Opponent类中,Update方法试图将Background.speed用作int,这会导致结果舍入:

int speedp = (int)b.speed + 1;
// result will be 3 due to rounding

换句话说:

int speedp = (int)2.001 + 1;
// result will be 3 due to rounding

Background.speed大于2.5之前,结果将始终为3.

要解决此问题,speedp将需要为双倍(或类似),因此精度不会因舍入而丢失。

相关问题