Have a bug with keyPressed

Trying to build a basic game allowing character to move about. For some reason using the following code if i hold done the "a" key when the character hits the left boundary i can no longer use the keys to control anything.

int x,y;
int vectX;
int vectY;


void setup(){

size(400,400);
x=100;
y=100;
}

void draw(){
  background(255);

  fill(255,0,0);
  ellipse(x,y,30,30);

  x=x+vectX;
  y=y+vectY;

  if(x<15 || x>width){
    vectX*=-1;
  }
  if (y<15 || y>height){
    vectY*=-1;
  }
}
 void keyPressed(){

   if(key=='w'){
     vectX=0;
     vectY=-1; 
   }
      if(key=='a'){
     vectX=-1;
     vectY=0; 
   }
      if(key=='d'){
     vectX=1;
     vectY=0; 
   }
      if(key=='s'){
     vectX=0;
     vectY=1; 
   }
 }
Tagged:

Answers

  • void keyPressed() is called when a key is pressed but at the end of draw. So, when you press 'a' and the ellipse in at x=15, you first redirect it with line #22 & #23, and immediately after, keyPressed() is called directs the ellipse to the left. So, in the next iteration of draw(), the ellipse will still be going left.

    To fix this, move lines #19 & #20 after line #27

  • The ellipse changes direction and just starts bouncing left to right. It is just that if a press a key the keyPressed() is no longer able to be called. I inserted a println() into key pressed and that stops working as well.

  • Ok i just tested on my Windows 7 machine and is working fine. Must be something to do with MacOS Sierra i will try updating to latest processing and then see if i can figure it out from there.

Sign In or Register to comment.