[SOLVED] Problems with PVectors

Hey all,

I am having some problems with changing the values with PVectors.
Here is my code:

Rocket rocket = new Rocket();

void keyPressed() {
  switch(key) {
  case 'w': 
    rocket.up(); 
  case 's': 
    rocket.down();
  case 'd': 
    rocket.right();
  case 'a': 
    rocket.left();
  }
}

void setup() {
  size(800, 800);
}

void draw() {
  background(0);
  rocket.show();
  rocket.updatePos();
}

And here is the rocket class:

class Rocket{
    PVector pos = new PVector(100, 100); 
    PVector acc = new PVector(0, 0);
    
    void show(){
      fill(0, 255, 0);
      ellipse(pos.x, pos.y, 8, 8);
    }
    
    void updatePos(){
      pos = new PVector(pos.x + acc.x, pos.y + acc.y);
    }
    
    void up(){
      acc.y--;
    }
    void down(){
      acc.y++;
    }
    void right(){
      acc.x++; 
    }
    void left(){
      acc.x--;  
    }
}

The rocket can move left and down just fine, but it can never move right or up. Any suggestions?

1 Like

This took me way too long to figure out. I thought I was going crazy, because your class definition was perfectly fine and yet all four direction-methods kept being called at once.

Basically, you forgot your breaks in the switch-conditional!

void keyPressed() {
  switch(key) {
  case 'w': 
    rocket.up();
    break;
  case 's': 
    rocket.down();
    break;
  case 'd': 
    rocket.right();
    break;
  case 'a': 
    rocket.left();
    break;
  }
}

If you don’t call the break, the entire sequence gets called, so the accelerations were being cancelled out.

5 Likes

Every now and then this fall-through behavior of switch can be useful (I first learned about it in loop unrolling and “Duff’s device”).

In Processing’s key methods you can use the switch fall-through behavior to concisely define groups of keys with the same functionality without writing a bunch of “or” statements:

  switch(key) {
  // up
  case UP: 
  case 'w': 
  case 'i': 
    forward();
    break;
  // down
  case DOWN: 
  case 's': 
  case 'k': 
    back();
    break;
  // action
  case ENTER:
  case RETURN:
  case ' ';
    action();
    break;
  }
3 Likes