Learn More

Wednesday, October 19, 2011

Moving Sprite Using Keyboard With SDL

rotate cannon
In this tutorial we will explain how to handle events in SDL. Before starting this topic, the user is expected to have read the topic about rotate image using sdl and basic using keyboard to control the event. We feel this topic should we make in order for event handling logic becomes easy to understand.

Previously described, each event is handled by sdl through SDL_Event. Actually, SDL_Event is the general handling of each event. When only using the keyboard as a source of events, it can be replaced with SDL_KeyboardEvent SDL_Event. However, if this event requires a lot of source events, SDL_Event is the key. After a successful event is handled by SDL_Event, sdl collect event information that is being delayed. This task can be performed by SDL_PollEvent or SDL_PeepEvent. SDL_PollEvent a logical order. It will be worth 1 if there are events that are being delayed, and is 0 if no.

Events information collected includes events from the keyboard, mouse, joystick, and others. However, we focus on the event information from the keyboard. Event information from the keyboard includes two types, namely SDL_KEYDOWN (when pressed) and SDL_KEYUP (when not pressed). To find out if the button is pressed or released, then it will be done by SDL_keysym. SDL needs to know the symbol keys are used (pressed or released), in this case SDLKey will read the entire keyboard symbols used. See the figure below
event keyboard handle

Practice

Now, let we doing simple practice, how to control game from keyboard. This pratice show to you different way to make your game move smooth or move step by step.

Moving sprite when presses a key

This practice you will see that sprite (barrel) will rotated step by step each time while you pressing a keyboard. This happen because we don't give specification condition for making smooth movement. Please see the code below



Making sprite move smooth

This practice will guide you how to make a sprite move smooth. Because in here, we give condition for making smooth movement. There are two key success for this. First, we create an array for event.key.keysym.sym, then we give condition true if pressed and false when released. Please see the code below



for more code of this tutorial, you can get by press keyboard and by hold keyboard here.

  1. i dont know about this , big thanks for share ,,

    ReplyDelete
  2. waduh belajar pemrogaman nih... saya sulit bgt bljr ini.... saya lgi kuliah... komputer sgt sulit belajar pemrogaman macam gini... klo mbak tahu bisa ngajarin saya gk???? thx dah berkomentar di blog saya

    ReplyDelete
  3. Tuk m_aulia, saya bukan seorang dosen, jadi tidak mungkin bagi kami mengajari mbak. nanti threelas gak kepegang. kami menyediakan sarana threelas untuk belajar dan diskusi bagi para pengguna. Diskusi bisa dilakukan melalui komentar blogger ataupun f8 comment.

    ReplyDelete