粒子系统(Particle System)
粒子系统类的实现Particle
粒子的一些基本属性的设置
//属性
PVector loc,speed,acc;//位置,速度,加速度
color col;
float rad;
float maxVel=2.0;//粒子最大速度
float w=500.0;
float h=500.0;
float f=1000.0;
带参数的构造函数,确定粒子的位置、速度和加速度的值
//构造函数
Particle(PVector _loc,PVector _speed,PVector _acc){
loc=_loc;
speed=_speed;
acc=_acc;
}
默认构造函数
Particle(){
loc=new PVector(random(width*1.2),random(height));
rad=random(TWO_PI);
speed=new PVector(0,0);
acc=new PVector(cos(rad),sin(rad));
}
粒子运动函数
void move(){
float deg=360.0*noise(
loc.x/w,
loc.y/h,
millis()/10000.0);
rad=radians(deg);
acc.set(cos(rad),sin(rad));
speed.add(acc);
if(speed.magSq()>maxVel){
speed.normalize();
speed.mult(maxVel);
}
loc.add(speed);
}
越界处理:超出窗口就随机一个窗口内的位置
void checkEdges(){
if(loc.x<0||loc.x>width||loc.y<0||loc.y>height){
loc.x=random(width*1.2);
loc.y=random(height);
}
}
渲染
void render(){
ellipse(loc.x,loc.y,2,2);
}
将运动,渲染,越界函数打包放在一个函数里
void run(){
move();
checkEdges();
render();
}
简单的粒子系统的实现
定义粒子数目,存放粒子的数组
//粒子数
int num = 1000;
//存放粒子的数组
Particle[] particles = new Particle[num];
在setup()函数中生成粒子
void setup() {
size(1024, 728, P3D);
noStroke();
//迭代生成所有粒子
for (int i=0; i<num; i++) {
PVector loc = new PVector(random(width*1.2), random(height));
float rad = random(TWO_PI);
PVector speed = new PVector(0, 0);
PVector acc = new PVector(cos(rad), sin(rad));
particles[i]= new Particle(loc, speed, acc);
}
}
粒子系统实现
void draw() {
//半透明背景
fill(0, 10);
noStroke();
rect(0, 0, width, height);
fill(255, 155);
//遍历数组,每一个粒子都run起来
for (int i=0; i<particles.length; i++) {
particles[i].run();
}
}
运行效果
粒子数:500
扫描二维码关注公众号,回复:
11138593 查看本文章
粒子数:1000
粒子数:2500
粒子数:5000
粒子数:10000