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 http://sol.gfxile.net/imgui/ch01.html (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.

Awesome!

2 Comments
July 16, 2010 @ 11:21 am

Very interesting post! If I’ll ever need a blinking cursor with SDL I’ll use your example!

Cheers!

Sebastian

July 16, 2010 @ 1:55 pm

@Sebastian
Thanks! I just thought that the solution is so nice and simple, I thought I’d share it