Problem with SDL_GetKeyState

Started by
1 comment, last by Wibbs 15 years, 1 month ago
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;
	CKernel::GetSingletonPtr()->AddEvent(e);
    }
}

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]);
}

bool CInputTask::KeyStillDown(int t_iIndex)
{
	return (m_uchCurrentKeys[t_iIndex])&&(m_uchOldKeys[t_iIndex]);
}
Advertisement
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);
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

This topic is closed to new replies.

Advertisement