这段代码编译,但是当没有时,拒绝跳球cout.当有a时cout,它会正确地使object(dot)跳转.这只是使用SDL创建超级原始游戏的一些练习
主循环:
while (!quit){
while (SDL_PollEvent(&event))
if ((event.type == SDL_QUIT) || ((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_ESCAPE)))
quit = true;
Uint8 * keystates = SDL_GetKeyState(NULL);
if (keystates[SDLK_LEFT])
dot.left();
if (keystates[SDLK_RIGHT])
dot.right();
if (keystates[SDLK_SPACE]){ // press spacebar to jump
if (!jumping){
jumping = true;
jump_time = 0; // new count - not an actual timer
SDL_Delay(1);
}
}
while (jumping && ((t.now() + 2) < 1000 / FPS)){ // while jumping and 2ms away from frame cap time
jump_time += dt; // float values. dt = .0002
// why its so low is beyond me
// if i dont have this line, the dot will not jump
std::cout << std::endl;
// G = 9.81
// MAX_HEIGT = 20
// X shift = sqrt(MAX_HEIGHT * 2 / G)
dot.offset.y = height - dot.offset.h - (-G / 2 * (jump_time - XSHIFT) * (jump_time - XSHIFT) + MAX_HEIGHT);
if (dot.offset.y > (height - dot.offset.h)){
jumping = false;
dot.offset.y = height - dot.offset.h;
}
}
SDL_FillRect(screen, NULL, 0xFFFFFF);
dot.blit(screen);
if (SDL_Flip(screen) == -1)
return 1;
if (t.now() < 1000 / FPS){ // cap frame rate
SDL_Delay(1000 / FPS - t.now());
t.start(); // reset timer
}
}
Run Code Online (Sandbox Code Playgroud)
有谁能解释为什么?我不明白为什么会这样.SDL与它有关吗?
我很确定这不是使用cout特有的东西.它只与使用cout所花费的时间有关.cout语句所处的内部循环没有控制它的速度.它只是控制跳跃的东西?2毫秒,对吗?
在那2毫秒期间,点经历了尽可能多的状态,然后你再做一个帧,在那里又得到2毫秒.重复该过程,直到点完成它的跳跃.
当cout语句在那里时,它可能占用了2毫秒的很大一部分,这意味着它需要更多的帧来完成它的跳转.
当取出cout语句时,循环进行得如此之快,以至于跳转在很少的帧中完成,可能只有一帧.因此,无论它是如此之快,你只是看不到它,或者它是如此之快,你不能看到它,因为它的屏幕不断更新之前完成.
我建议你制定一个机制来持续计时跳跃.