We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Im reading through this: http://natureofcode.com/book/chapter-2-forces/
and i was wondering if anyone can help me with Exercise 2.1:
Using forces, simulate a helium-filled balloon floating upward and bouncing off the top of a window. Can you add a wind force that changes over time, perhaps according to Perlin noise?
I understand I need to make the balloon float up. Ive chosen to have that start with a user key press. When this happens, I call this to apply the force up. The balloon bounces but I need to figure out how to make it bounce less, maybe adding an effect whereby the balloon bounce reduces the force with which it comes back up.
Also the bounce has a weird effect at the end where it sort of sinks into the top edge.
Here is the code. Could you point out suggestions at an entry level still please :-)
class Mover {
PVector location;
PVector velocity;
PVector acceleration;
Mover() {
location = new PVector(width/2,height-24);
velocity = new PVector(0,0);
acceleration = new PVector(0,0);
}
void update() {
velocity.add(acceleration);
location.add(velocity);
acceleration.mult(0);
}
void display() {
stroke(0);
strokeWeight(2);
fill(127);
ellipse(location.x, location.y, 48, 48);
}
void checkUserInput() {
if (key == CODED) {
if (keyCode == UP) {
println("Release balloon");
PVector helium = new PVector(0,-0.5);
mover.applyForce(helium);
} else if (keyCode == DOWN) {
println("down pressed");
}
} else {
println("not coded");
}
}
void checkEdges() {
if (location.x > width) {
} else if (location.x < 0) {
}
if (location.y > height) {
} else if (location.y < 25) {
velocity.y *= -1; //flip sign of velocity y.vector only temporarily
println("bounce...");
}
}
void applyForce(PVector force) {
acceleration.add(force);
}
}
Mover mover;
void setup() {
size(640,360);
mover = new Mover();
}
void draw() {
background(255);
mover.update();
mover.checkUserInput();
mover.checkEdges();
mover.display();
}
Answers
I recommend a new var int movementState;
it can have values like 0,1,2,3.....
you can name those values:
final int onGround=0;
final int rise=1;
final int onCeiling = 2;
final int driftingRight=3;
now say movementState=onGround;
In update you act accordingly to movementState
When the key is pressed or we are on the ceiling of a certain time has passed change movementState
This will give you better control
Ok lets say I set movementState=onGround. How would that make the ball less bouncy when it reaches the top?
movementState=onCeiling;
velocity.y = .2;
set a timer and let it bounce / sink shortly and then say movementState=driftingRight;