• 9
• 13
• 10
• 18
• 19

# Problem with SDL_GetKeyState

This topic is 3294 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm trying to implement my Input Manager in the same way as is demonstrated in the Enginuity Tutorials. This means that I am using PumpEvents and SDL_GetKeyState rather that SDL_PollEvent. The problem I am having is as follows. I can get it to detect if I have a key pressed for longer than one input update - i.e it was pressed last time, and it's also pressed this time. However, I can't get it to detect the first time a key was pressed. I would be grateful for any assistance with this, as I'm stumped. Thanks in advance, Wibbs The relevant code is:-
SDL_PumpEvents();

// copy the keystate array to the old version
memcpy (m_uchOldKeys,m_uchCurrentKeys, sizeof(unsigned char) *m_iKeyCount);

m_uchCurrentKeys=SDL_GetKeyState(NULL);

// use the event polling to detect SDL_QUIT
while (SDL_PollEvent(&m_Event))
{
if (m_Event.type==SDL_QUIT)
{
boost::shared_ptr<Event> e (new Event());
e.get()->iType=GAME_QUIT;
}
}

if(KeyDown(SDLK_LEFT))
{
// do some stuff
}

if(KeyStillDown(SDLK_LEFT))
{
// do some different stuff
}

With the two function calls:-
bool CInputTask::KeyDown(int t_iIndex)
{
return (m_uchCurrentKeys[t_iIndex])&&(!m_uchOldKeys[t_iIndex]);
}

{
return (m_uchCurrentKeys[t_iIndex])&&(m_uchOldKeys[t_iIndex]);
}

##### Share on other sites
I don't think this:
SDL_PumpEvents();memcpy (m_uchOldKeys,m_uchCurrentKeys, sizeof(unsigned char) *m_iKeyCount);m_uchCurrentKeys=SDL_GetKeyState(NULL);
Does what you expect.

SDL_GetKeyState() returns the same pointer each time you call it (the function simply returns the address of an internal static array). So after the call to memcpy(), the contents of m_uchOldKeys and m_uchCurrentKeys are the same, which means no key will ever be registered as having 'just been pressed'.

Something like this might work though (this assumes that m_uchCurrentKeys has the same type as m_uchOldKeys):
memcpy(m_uchOldKeys, m_uchCurrentKeys, sizeof(unsigned char) *m_iKeyCount);memcpy(m_uchCurrentKeys, SDL_GetKeyState(0), sizeof(unsigned char) *m_iKeyCount);

##### Share on other sites
Thank you for the explanation. I can see what I was doing wrong now, and adding a line similar to that you suggested has corrected the problem.

Thanks again,

Wibbs