SDL Application runs too fast

Hi all,

My really badSDL Program is nearing completion. I tested it on my faster main computer, only to discover that while it ran perfectly on my ancient, dusty old laptop, it ran ultra-fast on the better computer.

I have made a timer class that limits the fps to 20, but either it isn't functioning, or it's being buggy, or I'm just missing something really, really obvious...

This is my Timer class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Timer {
    private:

    int startTicks;
    int pausedTicks;
    bool paused;
    bool started;
    public:

    Timer() {
        startTicks=0;
        pausedTicks=0;
        paused=false;
        started=false;
    }

    void start() {
        started=true;
        paused=false;

        startTicks=SDL_GetTicks();
    }

    void stop() {
        started=false;
        paused=false;
    }

    void pause() {
        if ((started==true) and (paused==false)) {
            paused=true;

            pausedTicks=SDL_GetTicks()-startTicks;
        }
    }

    void unpause() {
        if (paused==true) {
            paused=false;

            startTicks=SDL_GetTicks()-pausedTicks;

            pausedTicks=0;
        }
    }

    int get_ticks() {
        if (started==true) {
            if (paused==true) {
                return pausedTicks;
            }
            else {
                return SDL_GetTicks()-startTicks;
            }
        }
        return 0;
    }

    bool is_started() {
        return started;
    }

    bool is_paused() {
        return paused;
    }
};


Then in main, I declare a Timer called fps. At the end of my game loop I check the frames
and modify them:
1
2
3
if (fps.get_ticks()<(1000/FRAMES_PER_SECOND)) {
    SDL_Delay((1000/FRAMES_PER_SECOND)-fps.get_ticks());
}


FRAMES_PER_SECOND is const int FRAMES_PER_SECOND=20;

Can you see anything wrong with this?

Thanks,
hnefatl
Last edited on
Do you restart the timer somewhere?
[Good] framerate regulators can be tricky.

Here's one I wrote forever ago that works pretty well:

http://www.cplusplus.com/forum/general/52753/#msg285842
closed account (zwA4jE8b)
hnefatl

place fps.start() at the beginning of the loop.
closed account (1yR4jE8b)
I don't use or know SDL, but shouldn't something like that have a VSYNC function in the library?
@Peter87 Nope; I let the timer run and don't stop it.

@Disch That does look good; I think it's a little too good for me to quite understand. For this program I'll stick to this one. If i get into more advanced programs i'll refer back to that one though. Thanks :)
Last edited on
@CreativeMFS Don't worry, I'm not that bad at C++! :-)

You know, in sfml the only line of code you'll need is
1
2
SetFrameLimit(Var)
UseVerticalSync(Bool)
Topic archived. No new replies allowed.