【发布时间】:2017-11-07 09:20:46
【问题描述】:
我正在尝试学习如何手动计算增量时间(自上次游戏循环更新以来的时间),但我一定是在某个地方误解了一些东西。我正在为一个 Arduino 项目执行此操作,但它同样适用于我猜想的任何语言或平台。
我定义了变量oldTime、currentTime 和deltaTime,每个游戏循环我都执行以下操作:
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;
}
【问题讨论】:
-
没有足够的信息,绘制背景一定有一些副作用,也许你的循环每次渲染时都会运行?
-
我添加了更多信息。