Processing程序中数组的使用

2025-10-24 15:59:36

1、首先说说为什么要使用数组

输入代码:

float x1 = -20;

float x2 = 20;

void setup() {

size(240, 120);

smooth();

noStroke();

}

void draw() {

background(0);

x1 += 0.5;

x2 += 0.5;

arc(x1, 30, 40, 40, 0.52, 5.76);

arc(x2, 90, 40, 40, 0.52, 5.76);

}

运行代码,效果是绘制了两个相同的物体,那么如果要绘制 100 个相同的物体,我们要将相同语句写 100 变吗?当然不是的,这种情况下,我们就需要引入数组的应用了。

Processing程序中数组的使用

2、使用数组来创建相同的对象

输入代码:

float[] x = new float[3000];

void setup() {

size(240, 120);

smooth();

noStroke();

fill(255, 200);

for (int i = 0; i < x.length; i++) {

x[i] = random(-1000, 200);

}

}

void draw() {

background(0);

for (int i = 0; i < x.length; i++) {

x[i] += 0.5;

float y = i * 0.4;

arc(x[i], y, 12, 12, 0.52, 5.76);

}

}

Processing程序中数组的使用

3、数组的使用方法:

创建变量:int x;

创建数组:int[] x;

创建数组并定义数组内的元素数量:int[] x = new int[2000];

数组的数据类型没有特别要求,我们可以使用各种数据类型,例如下面就是创建了 32 个 PImage 数组

PImage[] images = new PImage[32];

需要说明的是,数组的元素是从 0 开始编号的,如下图所示:

Processing程序中数组的使用

4、直接定义数组中的元素

输入代码:

float[] x = {-20, 20};

void setup() {

size(240, 120);

smooth();

noStroke();

}

void draw() {

background(0);

x[0] += 0.5; 

x[1] += 0.5; 

arc(x[0], 30, 40, 40, 1, 5.76);

arc(x[1], 90, 40, 40, 0.12, 5.76);

}

这里我们就在定义时,就确定了数组内的元素是什么,运行结果如下图所示

Processing程序中数组的使用

5、通过随机数来设置数组的元素,实现图形的随机变化

输入代码:

float[] gray;

void setup() {

size(240, 120);

gray = new float[width];

for (int i = 0; i < gray.length; i++) {

gray[i] = random(0, 255);

}

}

void draw() {

for (int i = 0; i < gray.length; i++) {

stroke(gray[i]);

line(i, 0, i, height);

}

}

Processing程序中数组的使用

6、用数组来存储鼠标的位置

输入代码:

int num = 60;

int x[] = new int[num];

int y[] = new int[num];

void setup() {

size(240, 120);

smooth();

noStroke();

}

void draw() {

background(0);

for (int i = x.length-1; i > 0; i--) {

x[i] = x[i-1];

y[i] = y[i-1];

}

x[0] = mouseX; 

y[0] = mouseY; 

for (int i = 0; i < x.length; i++) {

fill(i * 4);

ellipse(x[i], y[i], 40, 40);

}

}

程序中使用了移位,这是为了让数组有足够的空间来存储下一个值

Processing程序中数组的使用

7、创建图片数组,首先准备两个图片

输入代码:

int numFrames = 3; 

PImage[] images = new PImage[numFrames]; 

int currentFrame = 1;

void setup() {

size(300, 120);

for (int i = 1; i < images.length; i++) {

String imageName = nf(i, 3) + ".png";

images[i] = loadImage(imageName); 

}

frameRate(1);

}

void draw() {

image(images[currentFrame], 0, 0);

currentFrame++; 

if (currentFrame >= images.length) 

{

currentFrame = 1; 

}

}

将代码保存,并在代码文件夹中创建一个新的文件夹,命名为 data,将两张图片放置到文件夹中。如图所示:

Processing程序中数组的使用

Processing程序中数组的使用

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢