How to ignore all other keys and use only arrows in a game

I'll make a snake game and when I press any other key in keyboard the circle stops, I wan't to deactivate all other keys and allow only arrows to move the snake.

int x, y;
void setup()
{
  size(500,500);
}

void draw()
{

if (keyCode==UP)
  {
    y-=2;

  }

  if (keyCode==DOWN)
  {
    y+=2;
  }

  if (keyCode==LEFT)
  {
    x-=2;

  }

  if (keyCode==RIGHT)
  {
    x+=2;
  }

  ellipse(x,y,30,30);

}
Tagged:

Answers

  • Answer ✓

    @shideception you placed your key checking in the draw loop which means it will check the latest keycode, if you press your up key and then do nothing the latest keycode will de UP, but if you press 'c' it will stop moving your object since the latest pressed key was 'c'

    The way I would solve this is by making a speed and then turn your draw into this

      x += xSpeed;
      y += ySpeed;
      ellipse(x, y, 30, 30);
    

    and instead of checking for pressed keys in the draw loop I would put them in the keyPressed void like this

    void keyPressed() {
      if (keyCode==UP)
      {
        if (ySpeed != -2) { //check if it isn't already going up other wise you would go faster and faster
          ySpeed = -2; //set ySpeed -2 so the ellipse will move up
          xSpeed = 0; //setting xSpeed to 0 so you dont move side way and up at the same time
        }
      }
    
      if (keyCode==DOWN)
      {
        if (ySpeed != 2) {
          ySpeed = 2;
          xSpeed = 0;
        }
      }
    
      if (keyCode==LEFT)
      {
        if (xSpeed != -2) {
          xSpeed = -2;
          ySpeed = 0;
        }
      }
    
      if (keyCode==RIGHT)
      {
        if (xSpeed != 2) {
          xSpeed = 2;
          ySpeed = 0;
        }
      }
    }
    

    so comments on up for explanation, dont forget to declare the speed integers

  • edited November 2017

    I don't see the point of checking the current speed values. Just always assign new ones:

    void keyPressed() {
      if (keyCode==UP)
      {
          ySpeed = -2;
          xSpeed = 0;
      } 
      if (keyCode==DOWN)
      {
          ySpeed = 2;
          xSpeed = 0;
      } 
      if (keyCode==LEFT)
      {
          xSpeed = -2;
          ySpeed = 0;
      } 
      if (keyCode==RIGHT)
      {
          xSpeed = 2;
          ySpeed = 0;
      }
    }
    
  • @TfGuy44 you're right, It just to be x += 2; and then I checked to make sure it wont add more speed then 2 but since I changed it to x = 2; it doesnt matter,

Sign In or Register to comment.