我试图学习制作游戏(我是c ++的新手),但我陷入了这个问题:
我有2个线程用于渲染(我没有延迟,因此它将尽可能快地渲染帧),另一个线程用于更新和处理诸如按键之类的事件(并且我将延迟保持8个)毫秒,因此它将修复更新,因此与计算机fps无关), 现在,此线程在每次更新中将播放器向右移动1个像素。
代码:
#include <iostream>
#include "SDL.h"
#include "GameM.h"
#include <thread>
#undef main
GameM *game = nullptr;
void rendering() {
while (game->running()) {
game->render();
}
}
void updating() {
while (game->running()) {
game->handleEvents();
game->update();
SDL_Delay(8);
}
}
int main()
{
game = new GameM();
game->init("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640,400,SDL_WINDOW_SHOWN|SDL_WINDOW_BORDERLESS);
//thread initialize
std::thread rendering(rendering);
std::thread updating(updating);
//Makes main thread to wait to the threads to finish
rendering.join();
updating.join();
//cleans
game->clean();
return 0;
}
尽管我运行程序:
需要您的帮助,聪明的人:)
EDIT3:
GameM *game = nullptr;
const float FPS = 60.0;
const float desFPS = 1000.0 / 60.0;
Uint32 firstframe;
float delta;
void updating() {
while (game->running()) {
firstframe = SDL_GetTicks();
game->handleEvents();
game->update();
delta = SDL_GetTicks() - firstframe;
if (desFPS > delta) {
SDL_Delay(desFPS - delta);
}
}
}
int main()
{
game = new GameM();
game->init("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640,400,SDL_WINDOW_SHOWN|SDL_WINDOW_BORDERLESS);
std::thread updating(updating);
while (game->running()) {
game->render();
}
updating.join();
game->clean();
return 0;
}
void GameM::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
isRunning = false;
std::cout << "STOP" << std::endl;
break;
}
}
}
void GameM::update(){
dstR.x += 1;
}
void GameM::render() {
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, tex, NULL, &dstR); // render asset to window
SDL_RenderPresent(renderer);
}