Acceleration always ends at the initial location

I am curious why the rectangle always ends up at the original location. Why would it not continue past the origin and bounce off the other side? Thanks.

Mover m;

void setup() {
  size(640, 340);
  smooth();
  m = new Mover();
}

void draw() {
  m.update();
  m.display();
  m.checkEdges();
}

class Mover {
  PVector location;
  PVector velocity;
  PVector acceleration;

  Mover() {
    location = new PVector(width/2, height/2);
    velocity = new PVector(0, 0);
    acceleration = new PVector(0.03, 0.02);
  }
  void update() {
    velocity.add(acceleration);
    velocity.limit(5);
    location.add(velocity);
  }
  void display() {
    rect(location.x,location.y,20,20);
  }
  void checkEdges() {
    if (location.x > width) {
      location.x = width;
      velocity.x *= -1;
    }
    else if (location.x < 0) {
      velocity.x *= -1;
      location.x = 0;
    }
    if (location.y > height) {
      location.y = height;
      velocity.y *= -1;
    }
    else if (location.y < 0) {
      velocity.y *= -1;
      location.y = 0;
    }
  }
}
Tagged:

Answers

  • edited April 2014

    That puzzled me too! X_X Seems like we have to invert both velocity & acceleration, but not touch location! 3:-O
    I've re-written checkEdges() as confineToEdges(), so you can compare both: =:)

    // forum.processing.org/two/discussion/4260/
    // acceleration-always-ends-at-the-initial-location
    
    static final short DIAM = 20;
    static final float DAMP = .5;
    
    void confineToEdges() {
      if (location.x < 0 | location.x > width  - DIAM) {
        velocity.x *= -1.;
        acceleration.x *= -1.;
        update();
        velocity.mult(DAMP);
      }
    
      if (location.y < 0 | location.y > height - DIAM) {
        velocity.y *= -1.;
        acceleration.y *= -1.;
        update();
        velocity.mult(DAMP);
      }
    }
    
  • edited April 2014 Answer ✓

    The issue here (which I do not view as an "issue") is that there is a constant acceleration (think of it like a wind force) always pushing the mover to the right and down. For example if you started the mover with a particularly and left acceleration at 0,0 then it would perform as you expect.

    velocity = new PVector(1, 2);
    acceleration = new PVector(0,0);
    

    You might take a look at the chapter 2 examples which incorporate an applyForce() method. This is a bit more clear I think.

  • That makes sense, thanks for clarifying.

Sign In or Register to comment.