processing图形随机移动
时间: 2023-08-28 08:35:15 浏览: 45
您可以使用Processing的random()函数来生成随机的移动量,然后使用translate()函数将图形移动。以下是一个简单的例子,它使用random()函数在x和y方向上生成随机的移动量,然后将矩形移动到新的位置:
```
float x, y; // 矩形的位置
void setup() {
size(400, 400);
x = width/2;
y = height/2;
}
void draw() {
background(255);
// 生成随机的移动量
float xMove = random(-5, 5);
float yMove = random(-5, 5);
// 移动矩形
translate(xMove, yMove);
// 绘制矩形
rect(x, y, 50, 50);
// 更新矩形的位置
x += xMove;
y += yMove;
}
```
在该示例中,矩形的位置由变量x和y存储。在每次绘制循环中,使用random()函数生成随机的移动量,并将矩形移动到新的位置。然后,更新矩形的位置,以便在下一个绘制周期中移动到正确的位置。您可以根据需要调整随机移动的范围和速度。
相关问题
processing图形随意移动
您可以使用Processing的translate()函数来移动图形。translate()函数将坐标系的原点移动到指定的位置,然后您可以在新的位置上绘制图形。例如,以下代码将矩形向右移动50像素:
```
void setup() {
size(400, 400);
}
void draw() {
background(255);
// 移动坐标系
translate(50, 0);
// 绘制矩形
rect(0, 0, 50, 50);
}
```
您可以根据需要调整translate()函数的参数来移动图形的位置和方向。
processing随机图形代码
以下是一个简单的 Processing 随机图形代码示例:
```java
void setup() {
size(500, 500);
background(255);
}
void draw() {
// 随机生成图形的位置、大小和颜色
float x = random(width);
float y = random(height);
float size = random(50, 150);
color c = color(random(255), random(255), random(255), 100);
// 随机选择图形类型
int shapeType = int(random(3));
// 根据图形类型生成不同的图形
switch (shapeType) {
case 0:
// 画圆形
fill(c);
noStroke();
ellipse(x, y, size, size);
break;
case 1:
// 画矩形
fill(c);
noStroke();
rectMode(CENTER);
rect(x, y, size, size);
break;
case 2:
// 画三角形
fill(c);
noStroke();
triangle(x, y, x + size/2, y + size, x - size/2, y + size);
break;
}
}
```
这个示例程序会在窗口中随机生成不同颜色、大小和形状的图形。每次 `draw()` 函数被调用时,都会随机选择一个图形类型,然后根据类型生成对应的图形并显示在屏幕上。