【问题标题】:Using classes other variables that update in real time使用类其他实时更新的变量
【发布时间】:2013-12-27 02:23:58
【问题描述】:

我正在用 C# 用 monogame 制作一个自上而下的汽车游戏。 (我标记 XNA 是因为 monogame 也使用 XNA。完全一样)

游戏现在看起来像这样:

虽然我的车速有些问题。 我在背景类中有一个变量,它的速度正在增加,但是我试图对汽车做同样的事情,但是速度增加了 1,所以它有汽车移动得更远的错觉。我已将其包含在汽车的代码中:

Background b = new Background();

后台速度每帧增加'0.001',放入类的Update部分。

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”一样更新速度? 提前致谢。 (对不起,如果这很难理解)

【问题讨论】:

  • Console.WriteLine(b.speed) 给了你什么?还有b.speed的类型是什么?

标签: c# xna monogame


【解决方案1】:

通过查看变量类型可以发现问题:

  • 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 需要为双精度(或类似),以免因舍入而丢失精度。

【讨论】:

  • 这并没有解决问题。它仍然认为它是两个.. 似乎看不到更新类的内容是什么,只能看到变量设置的内容。所以 2. 所以如果我的背景在 5 点移动。汽车还在 3 点移动。
  • Background 类是否在整个应用程序中被多次创建?还是只创建一次并根据需要引用它,即从Opponent 类中?根据您的描述,Opponent 类中的 Background 类与正在更新的引用不同。
  • 是的,什么? Background 正在 game1 类以及其他类(例如 Oppenent?或者是的,Background 仅在 game1 类中创建,没有在哪里在应用程序中的其他地方?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多