We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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;
}
}
}
Answers
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: =:)
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.
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.