用processing写一段旋转粒子的代码
时间: 2023-08-13 15:06:29 浏览: 47
好的,请先确保你已经安装了Processing软件,然后按照以下步骤操作:
1. 创建一个新的Processing文件,并命名为“ParticleRotation”。
2. 设置画布大小为600x600,背景色为黑色:
```java
void setup() {
size(600, 600);
background(0);
}
```
3. 定义一个名为“Particle”的类,用来表示每一个粒子。包含粒子的位置、颜色和半径等信息。同时也定义一个名为“display”的方法,用来绘制粒子:
```java
class Particle {
float x, y; // 粒子的位置
float r; // 粒子的半径
color c; // 粒子的颜色
Particle(float x_, float y_, float r_, color c_) {
x = x_;
y = y_;
r = r_;
c = c_;
}
void display() {
noStroke();
fill(c);
ellipse(x, y, r, r);
}
}
```
4. 在主函数中定义一个名为“particles”的数组,用来保存所有的粒子。同时也定义一个名为“addParticle”的方法,用来添加新的粒子到数组中:
```java
Particle[] particles = new Particle[100];
void addParticle() {
float x = random(width);
float y = random(height);
float r = random(10, 20);
color c = color(random(255), random(255), random(255));
Particle p = new Particle(x, y, r, c);
particles[index++] = p;
}
```
5. 在主函数中定义一个名为“index”的变量,用来记录当前粒子数组中已经添加的粒子数量。同时也定义两个名为“angle”和“speed”的变量,分别表示粒子旋转的角度和速度:
```java
int index = 0;
float angle = 0;
float speed = 0.01;
```
6. 在主函数中,使用“addParticle”方法添加100个粒子到数组中:
```java
for (int i = 0; i < 100; i++) {
addParticle();
}
```
7. 使用“draw”函数来循环绘制每一个粒子。在“draw”函数中,首先清空画布,然后遍历所有的粒子,根据当前的旋转角度计算粒子的新位置,并调用“display”方法绘制粒子。最后更新旋转角度:
```java
void draw() {
background(0);
for (int i = 0; i < index; i++) {
Particle p = particles[i];
float x = cos(angle) * (p.x - width/2) - sin(angle) * (p.y - height/2) + width/2;
float y = sin(angle) * (p.x - width/2) + cos(angle) * (p.y - height/2) + height/2;
p.x = x;
p.y = y;
p.display();
}
angle += speed;
}
```
8. 运行程序,在窗口中可以看到旋转的粒子了。
完整代码如下:
```java
class Particle {
float x, y; // 粒子的位置
float r; // 粒子的半径
color c; // 粒子的颜色
Particle(float x_, float y_, float r_, color c_) {
x = x_;
y = y_;
r = r_;
c = c_;
}
void display() {
noStroke();
fill(c);
ellipse(x, y, r, r);
}
}
Particle[] particles = new Particle[100];
void setup() {
size(600, 600);
background(0);
for (int i = 0; i < 100; i++) {
addParticle();
}
}
int index = 0;
float angle = 0;
float speed = 0.01;
void draw() {
background(0);
for (int i = 0; i < index; i++) {
Particle p = particles[i];
float x = cos(angle) * (p.x - width/2) - sin(angle) * (p.y - height/2) + width/2;
float y = sin(angle) * (p.x - width/2) + cos(angle) * (p.y - height/2) + height/2;
p.x = x;
p.y = y;
p.display();
}
angle += speed;
}
void addParticle() {
float x = random(width);
float y = random(height);
float r = random(10, 20);
color c = color(random(255), random(255), random(255));
Particle p = new Particle(x, y, r, c);
particles[index++] = p;
}
```