This code compiles, but refuses to make a ball jump when there is no cout
. When there is a cout
, it properly makes the object (dot
) jump. This is just a bit of practice using SDL to create a super primitive game
Main loop:
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
}
}
Can anyone explain why? I don't understand why this is happening. Does SDL have something to do with it?
I'm pretty sure it's not something specific to using cout. It only has to do with the amount of time that using cout takes. That inner loop that the cout statement is in has nothing controlling it's pace. It just controls the jump for what? 2 milliseconds, right?
During that 2 milliseconds, the dot goes through as many states as it can, then you do another frame, where it get's another 2 milliseconds. That process is repeated until the dot completes it's jump.
When the cout statement is in there, it probably takes up a significant portion of that 2 milliseconds, meaning that it takes the dot more frames to finish it's jump.
When the cout statement is taken out, the loop just goes so fast, that the jump is completed in very few frames, possibly just one. So either it's so fast that you just don't see it, or it's so fast that you can't see it, because it's done before the screen ever updates.
I'd recommend you work out a mechanism for timing the jump consistently.
I'm guessing its more the std::endl part that matters. Implicitly, endl forces a flush of the stream, which ensures data is printed. See if SDL has something to flush the screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With