Processing 创建运动的物体

2025-11-17 06:42:16

1、编程实现物体从左到右的平滑移动

输入代码:

int radius = 40;

float x = -radius;

float speed = 0.5;

void setup() {

size(240, 120);

smooth();

ellipseMode(RADIUS);

}

void draw() {

background(0);

x += speed; // Increase the value of x

arc(x, 60, radius, radius, 0.52, 5.76);

}

Processing 创建运动的物体

Processing 创建运动的物体

2、物体的循环运动

输入代码:

int radius = 40;

float x = -radius;

float speed = 0.5;

void setup() {

size(240, 120);

smooth();

ellipseMode(RADIUS);

}

void draw() {

background(0);

x += speed; 

if (x > width+radius) { 

x = -radius; 

}

arc(x, 60, radius, radius, 0.52, 5.76);

}

注意这里使用了 if 判断语句,就是判断是否超出了设置的窗口,如果超出窗口,就重新设置物体的坐标,再次从起点开始运动;窗口坐标示意如下图所示:

Processing 创建运动的物体

3、碰到墙壁就翻转,并朝相反的方向移动

输入代码:

int radius = 40;

float x = 110;

float speed = 0.5;

int direction = 1;

void setup() {

size(240, 120);

smooth();

ellipseMode(RADIUS);

}

void draw() {

background(0);

x += speed * direction;

if ((x > width-radius) || (x < radius)) {

direction = -direction; // Flip direction

}

if (direction == 1) {

arc(x, 60, radius, radius, 0.52, 5.76); // Face right

} else {

arc(x, 60, radius, radius, 3.67, 8.9); // Face left

}

}

Processing 创建运动的物体

4、从屏幕上一个像素点移动到另一个像素点

输入代码:

int startX = 20; // Initial x-coordinate

int stopX = 160; // Final x-coordinate

int startY = 30; // Initial y-coordinate

int stopY = 80; // Final y-coordinate

float x = startX; // Current x-coordinate

float y = startY; // Current y-coordinate

float step = 0.005; // Size of each step (0.0 to 1.0)

float pct = 0.0; // Percentage traveled (0.0 to 1.0)

void setup() {

size(240, 120);

smooth();

}

void draw() {

background(0);

if (pct < 1.0) {

x = startX + ((stopX-startX) * pct);

y = startY + ((stopY-startX) * pct);

pct += step;

}

ellipse(x, y, 20, 20);

}

Processing 创建运动的物体

5、产生随机图形

输入代码:

void setup() {

size(240, 120);

smooth();

}

void draw() {

background(204);

for (int x = 20; x < width; x += 20) {

float mx = mouseX / 10;

float offsetA = random(-mx, mx);

float offsetB = random(-mx, mx);

line(x + offsetA, 20, x - offsetB, 100);

}

}

Processing 创建运动的物体

Processing 创建运动的物体

6、让物体随机移动到任意位置

输入代码:

float speed = 2.5;

int diameter = 20;

float x;

float y;

void setup() {

size(240, 120);

smooth();

x = width/2;

y = height/2;

}

void draw() {

x += random(-speed, speed);

y += random(-speed, speed);

ellipse(x, y, diameter, diameter);

}

Processing 创建运动的物体

7、控制物体的运动时间

输入代码:

int time1 = 2000;

int time2 = 4000;

float x = 0;

void setup() {

size(480, 120);

smooth();

}

void draw() {

int currentTime = millis();

background(204);

if (currentTime > time2) {

x -= 0.5;

} else if (currentTime > time1) {

x += 2;

}

ellipse(x, 60, 90, 90);

}

Processing 创建运动的物体

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