Variable getting set too late

Good evening

In the code below, when the object was drawn and I press a key, the object keeps moving to the previous direction for another frame and then switches to my new direction. How can I fix it, so the change takes place immeadiately? It's like: Frame moving up -> Arrow Left Key pressed -> Frame moving up -> Frame moving left. Should be: Frame moving up -> Arrow Left Key pressed -> frame moving left.

int direction = UP;

void setup()
{
  frameRate(1);
  //my code
}

void draw()
{
  //my code
  switch(direction)
  {
  case UP:
    //move object
    break;
  case DOWN:
    //move object
    break;
    //etc.
  }
  //more code to draw object
}

void keyPressed()
{
  if (key == CODED) {
    switch(keyCode)
    {
    case UP:
      direction = UP;
      break;
      //etc.
    }
  }
}

Answers

  • That is because your frame rate is low. If you increase the rate, I will bet it will respond the way you want.

    Kf

  • Why should it behave differently on higher framerates? The delay is still there, but less noticeable. I need the framerate low (<10) for the game to be playable.

  • Notice we cannot reproduce your observations as your code is not complete. Present an MCVE as it will help to provide the right feedback. From my experience, when you are working with low frame rates, your mouse and key response scales down to your set speed aka. everything is slower. If you are having problems making your game work at higher frame rates, then you should ask that question instead. However, for the time being, we will focus on the question at hand.

    Kf

  • Yes, more details / example.

    Why should it behave differently on higher framerates? The delay is still there, but less noticeable. I need the framerate low (<10) for the game to be playable.

    Well, key events are processed at the end of each frame. You can't change that.

    What you could try instead:

    1. set your framerate to 30 or 60 -- something nice and crisp.
    2. only draw once every n frames.
    3. this greatly increases your chance of catching a key event between draws.

    You can also control your key on/offs with booleans to make them a bit smoother so that you aren't relying on repeat keyboard events, which stutter.

Sign In or Register to comment.