Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange behavior of SDL_GetKeyState()
    primarykey
    data
    text
    <p>I'm trying to write a Pong clone in C++ using SDL. Basically, I wrote a simple engine that takes care of rendering and updating</p> <pre><code>void Player::update(Uint32 ticks, SDL_Event *event, Uint8 *keys) { if(keys[SDLK_UP]) { if(m_bounds.y &gt; 0) m_bounds.y -= 2.0f * (ticks / 1000.0f); } else if(keys[SDLK_DOWN]) { if(m_bounds.y &lt; (windowInfo.getHeight() - m_bounds.h)) m_bounds.y += 2.0f * (ticks / 1000.0f); } } </code></pre> <p>The problem is that when I press the UP key, everything works like a charm, but when I press the DOWN key, it doesn't work at all. I tried everything and after a couple of hours I noticed, that when I remove the ticks and add just 2.0f it works, but I don't know why, since the conditional for the UP key looks exactly the same, except it adds, instead of substracting. I've been trying to deal with this problem a couple of hours and still have not solved it. Do you have any idea what might be wrong?</p> <p>For completeness, I'm attaching some code that calls the Player::update function, so that you know a bit more.</p> <pre><code>void Engine::update() { ++m_numOfFrames; m_elapsedTime = SDL_GetTicks() - m_startTime; while(SDL_PollEvent(&amp;m_event)) { if(m_event.type == SDL_QUIT) { m_isRunning = false; } } if(m_keys[SDLK_ESCAPE]) { m_isRunning = false; } for(Entity *entity : m_entities) { entity-&gt;update(m_elapsedTime, &amp;m_event, m_keys); } m_startTime = SDL_GetTicks(); SDL_PumpEvents(); } </code></pre> <p>EDIT: I edited the code a bit to see all the values, the code looks like this now:</p> <pre><code>if(keys[SDLK_UP]) { if(m_bounds.y &gt; 0) { m_bounds.y -= 2.0f * (ticks / 1000.0f); std::cout &lt;&lt; 2.0f * (ticks / 1000.0f) &lt;&lt; " value of Y:" &lt;&lt; m_bounds.y &lt;&lt; std::endl; } } else if(keys[SDLK_DOWN]) { if(m_bounds.y &lt; (windowInfo.getHeight() - m_bounds.h)) { m_bounds.y += 2.0f * (ticks / 1000.0f); std::cout &lt;&lt; 2.0f * (ticks / 1000.0f) &lt;&lt; " value of Y:" &lt;&lt; m_bounds.y &lt;&lt; std::endl; } } </code></pre> <p>The result in console are pretty much the same for both, except for the DOWN conditional, the value of <code>m_bounds.y</code> doesn't change at all, it's always the same, although it's been added a line higher. The error must be on this line:</p> <pre><code>m_bounds.y += 2.0f * (ticks / 1000.0f); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload