Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » How to use a keyboard to move the picture in Allegro?

This thread is locked; no one can reply to it. rss feed Print
How to use a keyboard to move the picture in Allegro?
keprast
Member #16,794
January 2018

Maybe I just said it's too strange...

I know that Allegro can use “al_load_bitmap”to add image.
Like this:

image=al_load_bitmap(xxx.png);

I also know how to use the keyboard event.

How to do it, move xxx.png with a keyboard event?

NiteHackr
Member #2,229
April 2002
avatar

You load in an image, presumably smaller than the screen it is on. You set two variables like X for right and left movement, and Y for up and down movement, which tell Allegro where on screen is the upper left corner and you use them in the Allegro function which draws the image.

You then test for keyboard input, perhaps the arrow keys or WSAD or whatever you wish. When you press the key to move right, you add +1 to X and redraw the image, it will be drawn one to the right. If you press UP you would subtract -1 from Y and redraw etc.

While moving it around, be sure to test if the image will go off screen. For example, if you press RIGHT and that would move the image off screen, you wouldn't bother adding 1 to X. Same with the other directions.

I could show you code, but you'll learn more if you try doing the rest yourself.

---
"C is quirky, flawed, and an enormous success." - Dennis M. Ritchie

bamccaig
Member #7,536
July 2006
avatar

You basically already have this program written for you in the other thread. Instead of the automatic movement code that I hacked in which moves the sprite around the border of the screen, you'd want to comment that out or delete it and instead add some conditions to the event handling switch statement to modify the x and y coordinates when you press certain keys on the keyboard (the ESC key is already handled to give you an example of how you might do that).

I said:

                case ALLEGRO_EVENT_KEY_DOWN:
                    if(event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
                        running = 0;
                    }

                    break;

The faithful manual documents the macros/constants for the different keys on the keyboard. Instead of setting the running variable you'd want to add some number or subtract some number from either x or y which are used to tell Allegro where to draw the sprite in the program I offered.

Go to: