Chapter2-力学
程序员文章站
2022-03-05 12:20:53
...
效果演示
实现方法:
这个实验模拟的是气球上升碰到天花板反弹的效果,同时添加了一些随机的风力效果,是气球随风舞动。
1.构建Mover类
这里具体的做法不细述了,因为和chapter1非常类似,唯一有变化的是力的添加。力直接影响的是加速的,因此需要添加一个addforce函数,在每一帧对acceleration进行更新,同时,在update函数中将acceleration归零,避免力的叠加。
class Mover
{
PVector location;
PVector velocity;
PVector acceleration;
float topspeed;
Mover()
{
location =new PVector(random(width),random(height));
velocity=new PVector(0,0);
topspeed=4;
}
void update()
{
PVector mouse =new PVector(mouseX,mouseY);
PVector dir =PVector.sub(mouse,location);
dir.normalize();
dir.mult(0.5);
velocity.add(dir);
velocity.limit(topspeed);
location.add(velocity);
}
void display()
{
noStroke();
fill(velocity.x*10+10,velocity.y*10+10);
ellipse(location.x,location.y,velocity.x*10,velocity.y*10);
stroke(0);
fill(255);
ellipse(location.x,location.y,20,20);
}
void checkEdge()
{
if(location.x>width)
{
location.x=0;
}
else if (location.x<0)
{
location.x=width;
}
if(location.y>height)
{
location.y=0;
}
else if (location.y<0)
{
location.y=height;
}
}
}
2.在draw函数中调用
为了模拟出随机风力影响的效果,我设置了风每隔500帧吹动一次,风力大小和方向随机,每次风力持续50帧。
void draw() {
background(255);
if(n%500==0)
{
wind=new PVector(random(-0.3,0.3),random(0,0.3));
flow_flag=true;
flow_times=1;
}
for(Mover m:ms)
{
if(flow_flag)
{
if(flow_times!=50)
{
m.applyForce(wind);
flow_times++;
}
else
{
flow_flag=false;
}
}
PVector gravity = new PVector(0,-0.02);
m.applyForce(gravity);
m.update();
m.display();
m.checkEdges();
}
n++;
}
上一篇: TS码流解析-2-获取完整的TABLE