![]() | DirectFB Tutorials |
Moving a sprite with the cursor keys (without input buffer) |
#include <stdio.h> | |
#include <directfb.h> | |
static IDirectFB *dfb = NULL; |
(Globals) |
static IDirectFBInputDevice *keyboard = NULL; |
Our interface to the keyboard. |
int main (int argc, char **argv) | |
DFBSurfaceDescription dsc; |
(Locals) |
DFBInputDeviceKeyState escape = DIKS_UP; |
To quit the application when escape is pressed we store the key state here. |
int sprite_x, sprite_y, max_x, max_y; |
Here we store the current position of the sprite on the screen and the maximum x/y coordinates the sprite can have without being clipped. |
DFBCHECK (DirectFBInit (&argc, &argv)); |
(Initialize) |
DFBCHECK (dfb->GetInputDevice (dfb, DIDID_KEYBOARD, &keyboard)); |
Retrieve an interface to the keyboard so we can query key states. DIDID_KEYBOARD is the device id of the primary keyboard. |
DFBCHECK (dfb->CreateImageProvider (dfb, DATADIR"/tux.png", &provider)); |
(Load the sprite) |
max_x = screen_width - dsc.width; |
Calculate maximum x/y coordinates depending on screen resolution and sprite size. |
sprite_x = (screen_width - dsc.width) / 2; |
Initialize the sprite position by centering it on the screen. |
while (escape == DIKS_UP) |
Loop through until the escape key is pressed. |
DFBInputDeviceKeyState state; |
Local variable for key state queries. |
DFBCHECK (primary->FillRectangle (primary, 0, 0, screen_width, screen_height)); |
Clear the screen. |
DFBCHECK (primary->Blit (primary, tux, NULL, sprite_x, sprite_y)); |
Blit the sprite at its current position. |
DFBCHECK (primary->Flip (primary, NULL, DSFLIP_WAITFORSYNC)); |
Flip the front and back buffer, but wait for the vertical retrace to avoid tearing. |
DFBCHECK (keyboard->GetKeyState (keyboard, DIKI_LEFT, &state)); |
Query state of cursor keys and eventually move the sprite. |
DFBCHECK (keyboard->GetKeyState (keyboard, DIKI_RIGHT, &state)); | |
DFBCHECK (keyboard->GetKeyState (keyboard, DIKI_UP, &state)); | |
DFBCHECK (keyboard->GetKeyState (keyboard, DIKI_DOWN, &state)); | |
if (sprite_x < 0) |
Now make sure we didn't move the sprite out of the screen. |
DFBCHECK (keyboard->GetKeyState (keyboard, DIKI_ESCAPE, &escape)); |
Query state of escape key. |
keyboard->Release (keyboard); |
Release the keyboard. |
tux->Release (tux); |
(Release) |
return 23; |
(C) Copyright by convergence GmbH |
![]() |