前言
在《代码本色》的第4章 粒子系统 中,主要讲到了粒子系统的实现、多态和继承实现面向对象以及通过力的作用体现自然系统。以下为第4章的内容目录:
针对粒子系统的实现、多态和继承实现面向对象以及通过力的作用体现自然系统,我展开了自己的习作。
关于习作
学习了《代码本色》第4章 粒子系统 的内容之后,我想要在我的习作中表现的元素有:
- 鼠标的交互
- 粒子系统的生成
- 随机点的生成
- 排斥力的体现
其中,鼠标的交互和粒子系统的生成,体现在我鼠标在界面中移动即在我鼠标位置生成粒子系统;随机点的生成体现在界面中随机生成点圈圈;排斥力体现在界面中的大圆,所有的点(包括随机生成的和粒子系统生成的)经过界面时都会绕开大圆(排斥)。
下面是效果图和具体代码实现:
可以看到,排斥力很明显。
Particle.pde
class Particle {
PVector position;
PVector velocity;
PVector acceleration;
float lifespan;
float r = 6;
float mass = 1; // Let's do something better here!
Particle(PVector l) {
acceleration = new PVector(0,0);
velocity = new PVector(random(-1,1),random(-2,0));
position = l.get();
lifespan = 255.0;
}
Particle(float x, float y) {
acceleration = new PVector();
velocity = PVector.random2D();
position = new PVector(x, y);
lifespan = 255.0;
}
void run() {
update();
display();
}
void applyForce(PVector force) {
PVector f = force.get();
f.div(mass);
acceleration.add(f);
}
// Method to update position
void update() {
velocity.add(acceleration);
position.add(velocity);
acceleration.mult(0);
lifespan -= 2.0;
}
// Method to display
void display