Search code examples
processing

Processing-A shape is selected by either pressing a key ‘1’ or or key ‘2’ so that shape 1 or shape 2 can be picked up respectively


Draw two shapes on the sketch (e.g. a rectangle and a circle). Use the UP, DOWN, LEFT and RIGHT keys to control the movement of the selected shape. A shape is selected by either pressing a key ‘1’ or or key ‘2’ so that shape 1 or shape 2 can be picked up respectively.I want to select the shape by pressing the key "1" or "2", but they cannot run.`

int x = 0;
int y = 0;
int ex= 0;
int ey= 0;
 
void setup(){
  size (400, 400);  
}
 
void draw(){
  background(80);
  rect(x, y, 25,25);
  ellipse(50, 50, 50, 50);
}
 
void keyPresse() {
  if ( (key == '1')) {
    if (keyCode == UP) {
      y -= 10;
    } else if (keyCode == DOWN) {
      y += 10;
    } else if (keyCode == LEFT) {
      x -= 10;
    } else if (keyCode == RIGHT) {
      x += 10;
    }  
  } else if ((key == '2')){
      if (keyCode == UP) {
      ey -= 10;
    } else if (keyCode == DOWN) {
      ey += 10;
    } else if (keyCode == LEFT) {
      ex -= 10;
    } else if (keyCode == RIGHT) {
      ex += 10;
    } 
  }
}

Solution

  • There is a typo. The name of the key board callback is keyPressed. However, there are also some logical issues.


    Crate an array for the x and y coordinates. And an index variabel (shape_i):

    int x[] = new int[]{100, 100};
    int y[] = new int[]{200, 100};
    int shape_i = 0; 
    

    Draw the shapes on its position. (x[0], y[0]) is the position of the rectangle and (x[1], y[1]) is the position of the ellipse:

    void draw(){
      background(80);
      rect(x[0], y[0], 25, 25);
      ellipse(x[1], y[1], 50, 50);
    }
    

    Change the index (shape_i) when 1 or 2 is pressed. Change (x[shape_i], y[shape_i]) when an arrow key is pressed:

    void keyPressed() {
      if (key == '1') {
        shape_i = 0;
      } else if (key == '2') {
        shape_i = 1;
      } else if (keyCode == UP) {
        y[shape_i] -= 10;
      } else if (keyCode == DOWN) {
        y[shape_i] += 10;
      } else if (keyCode == LEFT) {
        x[shape_i] -= 10;
      } else if (keyCode == RIGHT) {
        x[shape_i] += 10;
      }
    }
    

    Complete example:

    int x[] = new int[]{100, 100};
    int y[] = new int[]{200, 100};
    int shape_i = 0;  
     
    void setup(){
      size (400, 400);  
    }
     
    void draw(){
      background(80);
      rect(x[0], y[0], 25, 25);
      ellipse(x[1], y[1], 50, 50);
    }
     
    void keyPressed() {
      if (key == '1') {
        shape_i = 0;
      } else if (key == '2') {
        shape_i = 1;
      } else if (keyCode == UP) {
        y[shape_i] -= 10;
      } else if (keyCode == DOWN) {
        y[shape_i] += 10;
      } else if (keyCode == LEFT) {
        x[shape_i] -= 10;
      } else if (keyCode == RIGHT) {
        x[shape_i] += 10;
      }
    }