Blinking Cursors

July 16, 2010

When having some sort of keyboard input it is always helpful to have a blinking cursor, so that the user knows where he/she/it is typing. This is usually shown by a blinking pipe ‘|’ or underscore ‘_’ symbol. In my current asteroids I didn’t bother with the blinking and simply appended a static underscore to the current input. However I was just reading a nice post about immediate GUIs at (very interesting way of programming a game user interface!), which also had a very nice trick to have a blinking mouse cursor with pretty much no effort. You find it in chapter 7 of that tutorial.

The trick is:

std::string name_output (mPlayerNameInput);
if ((SDL_GetTicks() >> 8) & 1)
	name_output += "_";
DrawGLString(xpos, ypos, name_output.c_str());

SDL_GetTicks() is the time function of the SDL library and simply returns the number of milliseconds passed since the initialization of the SDL library. By shifting the value of the function to the right by 8, the resulting expression in line 2 alternates now between true and false each 256 milliseconds. If you want the blinking every half seconds, shift it by 9 bits.