Sign in to follow this  
coderWalker

SDL Text input

Recommended Posts

I am constructing a screen for the player to enter their name before the main game begins. I have the sprites, background, and the text all working. I have now realized I have no idea how to get text from the user. How would one get some text, a string, or chars from the user. I can have separate chars and string them together myself, just getting them is the hard part. Ideas? Will i have to have a switch statement with 52 cases? I hope not

Thanks coderwalker

Share this post


Link to post
Share on other sites
Take a look at the SDL event handlers SDL_PollEvent or SDL_WaitEvent depending on the situation. It has been my experience that games benefit more from using SDL_PollEvent since SDL_WaitEvent is a blocking call (think modal dialog box).

SDL_PollEvent will allow you to handle keyboard events in the order they happen. SDL_EnableKeyRepeat is useful for making the input fields feel more like regular input fields since otherwise you will only get one event per keypress.

SDL_GetKeyState is more useful for grabbing the current state of keys at a specific point in time. This tends to be useful in conjunction with the events as opposed to by itself although many people have success using this instead of events for input handling. It really depends on your specific needs.

Share this post


Link to post
Share on other sites
You can use SDL_EnableUNICODE() and then use the following function (which I pieced together from the SDL docs a long time ago, I have no link):

char getUnicodeValue( const SDL_KeyboardEvent &key )
{
assert( SDL_EnableUNICODE(SDL_QUERY) == SDL_ENABLE );
// magic numbers courtesy of SDL docs :)
const int INTERNATIONAL_MASK = 0xFF80, UNICODE_MASK = 0x7F;

int uni = key.keysym.unicode;

if( uni == 0 ) // not translatable key (like up or down arrows)
{
// probably not useful as string input
// we could optionally use this to get some value
// for it: SDL_GetKeyName( key );
return 0;
}
else if( ( uni & INTERNATIONAL_MASK ) == 0 )
{
return static_cast<char>(uni & UNICODE_MASK);
}
else // we have a funky international character. one we can't read :(
{
// return 0 to inform the caller that we can't deal with this key.
return 0;
}
}



Your code simply needs to check if getUnicodeValue() returns non zero, and then append it to the text string.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this