Handling Keyboard and Mouse Events in SDL2
Trying to decipher keyboard and mouse events in SDL2? Here's how to handle them.
Join the DZone community and get the full member experience.
Join For Freehi there! in this article, we’ll learn how to handle keyboard and mouse events, and we’ll use them to move an object around the window. hooray!
we’ll start with an image. i made this 64×64 bitmap:
as you can see, i can’t draw to save my life. but since this is a bitmap, we don’t need the sdl_image extension.
once you have an image, you’ll want to create a new visual studio project, wire it up to work with sdl2, and then add some code to display a window and the spaceship in it. if you don’t remember how, these past articles should help:
- “ setting up sdl2 with visual studio 2015 “
- “ showing an empty window in sdl2 “
- “ displaying an image in an sdl2 window “
you should end up with code that looks something like this:
#include <sdl.h>
int main(int argc, char ** argv)
{
// variables
bool quit = false;
sdl_event event;
int x = 288;
int y = 208;
// init sdl
sdl_init(sdl_init_video);
sdl_window * window = sdl_createwindow("sdl2 keyboard/mouse events",
sdl_windowpos_undefined, sdl_windowpos_undefined, 640, 480, 0);
sdl_renderer * renderer = sdl_createrenderer(window, -1, 0);
sdl_surface * image = sdl_loadbmp("spaceship.bmp");
sdl_texture * texture = sdl_createtexturefromsurface(renderer,
image);
sdl_freesurface(image);
sdl_setrenderdrawcolor(renderer, 255, 255, 255, 255);
// handle events
while (!quit)
{
sdl_waitevent(&event);
switch (event.type)
{
case sdl_quit:
quit = true;
break;
}
sdl_rect dstrect = { x, y, 64, 64 };
sdl_renderclear(renderer);
sdl_rendercopy(renderer, texture, null, &dstrect);
sdl_renderpresent(renderer);
}
// cleanup sdl
sdl_destroytexture(texture);
sdl_destroyrenderer(renderer);
sdl_destroywindow(window);
sdl_quit();
return 0;
}
you’ll also want to place spaceship.bmp into your debug folder (along with sdl2.dll ) so that the program can find the files it needs..
once you actually run the program, you should see this:
i set the window’s background to white to match the spaceship’s white background by setting the clear colour using sdl_setrenderdrawcolor() , and then calling sdl_renderclear() to clear the window to that colour.
in order to handle keyboard and mouse events, we need an
sdl_event
. well, what do you know: we have been using one all along, in order to take action when the window is closed. what we need now is to handle a different event type. so let’s add a new
case
statement after the one that handles
sdl_quit
:
case sdl_keydown:
break;
within this
case
statement, let us now determine which key was actually pressed, and move the spaceship accordingly:
case sdl_keydown:
switch (event.key.keysym.sym)
{
case sdlk_left: x--; break;
case sdlk_right: x++; break;
case sdlk_up: y--; break;
case sdlk_down: y++; break;
}
break;
if you now run the program, you’ll find that you can move the spaceship using the arrow keys:
you’ll notice that it seems to move pretty slowly, and you have to keep pressing for quite a while to make any significant movement. now, in your code, replace sdl_waitevent with sdl_pollevent :
now, try running it again:
swoosh! in less than half a second, the spaceship hits the edge of the window. it’s actually too fast. to get this down to something manageable, add a small delay at the beginning of your
while
loop:
sdl_delay(20);
sdl_pollevent() is better than sdl_waitevent() when you want to continuously check (i.e. poll ) for events, but it consumes more cpu power (you can see this if you open task manager). sdl_waitevent() is okay when your window is mostly sitting idle so you don’t need to check for events that often.
handling mouse events is also very easy. all you need to do is handle the appropriate event. let’s see how to handle a mouse click:
case sdl_mousebuttondown:
switch (event.button.button)
{
case sdl_button_left:
sdl_showsimplemessagebox(0, "mouse", "left button was pressed!", window);
break;
case sdl_button_right:
sdl_showsimplemessagebox(0, "mouse", "right button was pressed!", window);
break;
default:
sdl_showsimplemessagebox(0, "mouse", "some other button was pressed!", window);
break;
}
break;
and this is what happens when you run it, and click somewhere in the window:
you can also track mouse motion and obtain the current coordinates of the mouse pointer. this is useful when moving things with the mouse (e.g. moving an object by mouse-dragging it). the following code obtains the mouse coordinates and displays them in the window title:
case sdl_mousemotion:
int mousex = event.motion.x;
int mousey = event.motion.y;
std::stringstream ss;
ss << "x: " << mousex << " y: " << mousey;
sdl_setwindowtitle(window, ss.str().c_str());
break;
note that you’ll need to add the following at the top of your main.cpp to make the above code work:
#include <sstream>
you will now notice the mouse coordinates in the window title:
wonderful! you should now have an idea of how to capture and handle keyboard and mouse events in sdl2. we will see more of these in an upcoming article dealing with drawing pixels in the window, so stay tuned to learn more!
this article was originally posted as “ sdl2: keyboard and mouse movement (events) ” at programmer’s ranch on 12th february 2014. it is slightly updated here. the source code and spaceship bitmap are available at the gigi labs bitbucket repository .
Published at DZone with permission of Daniel D'agostino, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments