I have an object at position (x,x). Using SDL keyboard events every time the user presses one of the arrow keys the objects is to be translated (via a glTranslatef() call for the x and y axes) by a constant factor (for example: 10).

Note: I take the top left corner of the SDL window to be my (0,0) position

  • Single press of left arrow key - decrease X of object by 10
  • Single press of right arrow key - increase X of object by 10
  • Single press of up arrow key - decrease Y of object by 10
  • Single press of down arrow key - decrease Y of object by 10

In order to allow diagonal movement I added four boolean flags (one per arrow key) that are set to true when the SDL_KEYDOWN event for the respective key is detected. After that I do the following (width and height are the size of the texture that represents my object on the screen):

if(keyLeft) {
  if(x >= 10+width/2) x -= 10;  // Check if the object doesn't go outside the window and translate
  else x = width/2;
if(keyRight) {
  if(x < 640-width/2) x += 10;
  else x = 640-width/2;
if(keyUp) {
  if(y >= 10+height/2) y -= 10;
  else y = height/2;
if(keyDown) {
  if(y < 480-height/2) y += 10;
  else y = 480-height/2;

It's working fine. The problem is that when I change the movement direction (for example from a movement in (x++,y++) to (x++,y) direction) I have to press the second key (or key combo) again in order to execute the second movement.

Any ideas how can I fix this? I realize that doing things the way I described above still results in choppy movement due to the limited movement directions, not taking factors such as speed and acceleration into account but it will do for now (prototype stage).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.