This is the third chapter of the book "The Nature of Code" about friction and resistance, I don't know what the problem is, as a beginner this is my first problem I can't solve, so I ask you for help.THANKS!

please format code with </> button * homework policy * asking questions

这是《The Nature of Code》书中第三章关于摩擦力与阻力的作业,我不知道哪里有问题,作为初学者这是我的第一个问题我没有办法去解决所以在这里求助大家。谢谢大家!

Mover movers = new Mover[100];
Liquid liquid;
void setup(){
size(640,320);
smooth();
for(int i =0;i<movers.length;i++){
movers[i] = new Mover(random(0.1,5),0,0);
}
liquid = new Liquid(0,height,2,height/2,0.1);
}

void draw(){
background(255);
liquid.display();
PVector wind=new PVector(0.01,0);
// PVector gravity=new PVector(0,0.1);
for(int i =0;i<movers.length;i++){
if(movers[i].isInside(liquid)){
movers[i].drag(liquid);
}
float m =0.1*movers[i].mass;
PVector gravity = new PVector(0,m);
float c =0.1;
PVector friction = movers[i].velocity.get();
friction.mult(-1);
friction.normalize();
friction.mult(c);

movers[i].applyForce(friction);
movers[i].applyForce(wind);
movers[i].applyForce(gravity);
movers[i].update();
movers[i].display();
movers[i].checkEdges();
}
}

class Mover{
PVector location;
PVector velocity;
PVector acceleration;
float mass;
Mover(float m,float x,float y){
mass= m;
location = new PVector(x,y);
velocity = new PVector(0,0);
acceleration = new PVector(0,0);
}
void applyForce(PVector force){
PVector f = PVector.div(force,mass);
acceleration.add(f);
}
void update(){
velocity.add(acceleration);
location.add(velocity);
acceleration.mult(0);
}
void display(){
stroke(0);
fill(174);
ellipse(location.x,location.y,mass16,mass16);
}
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){
velocity.y*=-1;
location.y = height;
}
}
}

class Liquid{
float x,y,w,h;
float c;
PVector acceleration;
float mass;
PVector location;
PVector velocity;
Liquid(float x_,float y_,float w_,float h_,float c_){
x=x_;
y=y_;
w=w_;
h=h_;
c=c_;
}
void display(){
noStroke();
fill(174);
rect(x,y,w,h);
}
void applyForce(PVector force){
PVector f = PVector.div(force,mass);
acceleration.add(f);
}

boolean isInside(Liquid l){
if(location.x>l.x && location.x<l.x+l.w && location.y>l.y && location.y<l.y+l.h){
return true;
}else{
return false;
}
}

void drag(Liquid l){
float speed = velocity.mag();
float dragMagnitude = l.cspeedspeed;
PVector drag = velocity.get();
drag.mult(-1);
drag.normalize();
drag.mult(dragMagnitude);
applyForce(drag);
}
}

1 Like

Hello,

The answer is here:
https://natureofcode.com/book/chapter-2-forces/

The chapter tells you which class to put the functions in.

:)