Disable mouse / cursor detection

Viewed 213

I'm making a simple Pong game.

When I ran the program, all the moves are perfect (the moving are not too fast nor too slow).

However, when I move my cursor around, the movement are faster which making the game much harder.

while (enable_loop)
        {
            Ticks = SDL_GetTicks();
            while (SDL_PollEvent(&any_event))
            {
                if (any_event.type == SDL_QUIT)
                {
                    enable_loop = false;
                }

                // Process keyboard event
                keyPressed = SDL_GetKeyboardState(NULL);

                if (keyPressed[SDL_SCANCODE_ESCAPE])
                {
                    enable_loop = false;
                }
                if (keyPressed[SDL_SCANCODE_UP] )
                {
                    player2.Update(25);
                }
                if (keyPressed[SDL_SCANCODE_DOWN])
                {
                    player2.Update(-25);
                }
                if (keyPressed[SDL_SCANCODE_W])
                {
                    player1.Update(20);
                }
                if (keyPressed[SDL_SCANCODE_S])
                {
                    player1.Update(-20);
                }
            }
            Grouping.update(surface, background);
            SDL_UpdateWindowSurface(window);
            limitFPS(Ticks);
        }
    }

Note : I've tried SDL_Delay(5) but the movement are too junky and jumping around, not usable :/

This game does not require mouse and I just may plug out my mouse, but I'm asking this for my experience and knowledge purposes.

I've used SDL_ShowCursor(SDL_DISABLE), SDL_CaptureMouse(SDL_FALSE) and limit my FPS to 60.

The effect is lessen but still noticeable.

How do I disable mouse detection or any code that will stop the effect?

1 Answers

Move the keyPressed checks outside the SDL_PollEvent() loop:

while (enable_loop)
{
    Ticks = SDL_GetTicks();
    while (SDL_PollEvent(&any_event))
    {
        if (any_event.type == SDL_QUIT)
        {
            enable_loop = false;
        }
    }

    // Process keyboard event
    keyPressed = SDL_GetKeyboardState(NULL);

    if (keyPressed[SDL_SCANCODE_ESCAPE])
    {
        enable_loop = false;
    }
    if (keyPressed[SDL_SCANCODE_UP] )
    {
        player2.Update(25);
    }
    if (keyPressed[SDL_SCANCODE_DOWN])
    {
        player2.Update(-25);
    }
    if (keyPressed[SDL_SCANCODE_W])
    {
        player1.Update(20);
    }
    if (keyPressed[SDL_SCANCODE_S])
    {
        player1.Update(-20);
    }

    Grouping.update(surface, background);
    SDL_UpdateWindowSurface(window);
    limitFPS(Ticks);
}

That way you're only processing keyboard input once per frame instead of once per event.

Related