手动计算增量时间

Manually calculating delta time

我正在尝试学习如何手动计算增量时间(自上次游戏循环更新以来的时间),但我一定是在某处误解了一些东西。我正在为一个 Arduino 项目做这个,但我猜它同样适用于任何语言或平台。

我定义了变量 oldTimecurrentTimedeltaTime,每个游戏循环我都执行以下操作:

void loop() {
   oldTime = currentTime;  // Save time from last loop.
   currentTime = millis(); // Time since program began.
   deltaTime = currentTime - oldTime; // Calculate time taken by game loop.
}

然后,当我使用它们来翻译精灵时,我将我的精灵速度乘以 deltaTime。但是,它不会导致速度独立于屏幕上绘制的内容。当我有一个布满瓦片的背景时,速度很快,但是当我根本不画背景时,精灵速度真的很慢。

我是不是误会了什么?

非常感谢您的帮助!

编辑:添加更多信息.....背景只是一个在屏幕上重复的图块。所以有背景会增加绘图时间,因此应该增加 deltaTime。所有绘图都在 loop 函数的末尾完成。

编辑 2:我不妨添加整个代码。

#include <Arduboy.h>
Arduboy arduboy;

const unsigned char background[] PROGMEM = {
  0x81, 0x00, 0x12, 0x40, 0x4, 0x11, 0x00, 0x4,
};
const unsigned char player[] PROGMEM = {
  0x00, 0x00, 0x00, 0x00, 0x34, 0xfc, 0x8f, 0x34, 0x6, 0x36, 0x8e, 0x94, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2, 0x1e, 0xe6, 0xa3, 0xda, 0x83, 0xc4, 0xb8, 0x00, 0x00, 0x00, 0x00,
};

int playerX;
int playerY;

unsigned long currentTime = 0;
unsigned long oldTime = 0;

void setup() {
  arduboy.begin();
  arduboy.clear();
  ResetGame();
}

void loop() {
  oldTime = currentTime;
  currentTime = millis();
  unsigned long deltaTime = currentTime - oldTime;

  arduboy.clear();
  for (int i = 0; i < 128; i += 8) {
    for (int j = 0; j < 64; j += 8) {
      arduboy.drawBitmap(i, j, background, 8, 8, WHITE);
    }
  }
  arduboy.fillRect(playerX + 4, playerY, 8, 16, BLACK);
  arduboy.drawBitmap(playerX, playerY, player, 16, 16, WHITE);
  arduboy.setCursor(0, 0);
  arduboy.print(arduboy.eachFrameMillis);
  if (arduboy.pressed(LEFT_BUTTON))
    playerX -= deltaTime;
  if (arduboy.pressed(RIGHT_BUTTON))
    playerX += deltaTime;
  if (arduboy.pressed(UP_BUTTON))
    playerY -= deltaTime;
  if (arduboy.pressed(DOWN_BUTTON))
    playerY += deltaTime;
  if (arduboy.pressed(A_BUTTON) and arduboy.pressed(B_BUTTON))
    ResetGame();

  arduboy.display();
}

void ResetGame()
{
  playerX = 5;
  playerY = 10;
  return;
}

好吧,我设法自己修复了它。我只是将字符位置变量更改为浮点数而不是整数,并将时间变量更改为浮点数而不是长整数。不过我真的不明白为什么会这样。