首页 > 解决方案 > 为什么此处理代码会创建递减轨迹?

问题描述

我正在通过Processing学习Java。

代码执行以下操作。

1) 调用 Setup 并初始化大小为 700,300 的窗口。

2) 使用设置中的 for 循环初始化多个点,并给出随机速度。

3) 自动调用draw函数。它是一个循环函数。它被一次又一次地调用。它每次都用一个黑色矩形填充空间,并绘制所有圆圈并更新它们的位置。

4) 由于每次调用draw() 时rect() 命令都会清屏,所以它必须只显示一个粒子并且没有轨迹。 但确实如此。

我遇到了其中一个教程,代码如下

Spot[] spots; // Declare array
void setup() {
  size(700, 100);
  int numSpots = 70; // Number of objects
  int dia = width/numSpots; // Calculate diameter
  spots = new Spot[numSpots]; // Create array
  for (int i = 0; i < spots.length; i++) {
    float x = dia/2 + i*dia;
    float rate = random(0.1, 2.0);
    // Create each object
    spots[i] = new Spot(x, 50, dia, rate);
  }
  noStroke();
}
void draw() {
  fill(0, 12);
  rect(0, 0, width, height);
  fill(255);
  for (int i=0; i < spots.length; i++) {
    spots[i].move(); // Move each object
    spots[i].display(); // Display each object
  }
}
class Spot {
  float x, y;         // X-coordinate, y-coordinate
  float diameter;     // Diameter of the circle
  float speed;        // Distance moved each frame
  int direction = 1;  // Direction of motion (1 is down, -1 is up)

  // Constructor
  Spot(float xpos, float ypos, float dia, float sp) {
    x = xpos;
    y = ypos;
    diameter = dia;
    speed = sp;
  }

  void move() {
    y += (speed * direction); 
    if ((y > (height - diameter/2)) || (y < diameter/2)) { 
      direction *= -1; 
    } 
  }

  void display() {
    ellipse(x, y, diameter, diameter);
  }
}

它产生这个输出:

在此处输入图像描述

我不明白为什么它会创建那些轨迹,而那些轨迹就会消失。直观地说,应该只有一个点是可见的,因为

for (int i=0; i < spots.length; i++) {
spots[i].move(); // Move each object
spots[i].display(); // Display each object
}

请指出导致这种情况发生的代码行?我没有任何线索。

参考:https ://processing.org/tutorials/arrays/ @Arrays:Casey Reas 和 Ben Fry

标签: javaarraysoopprocessingblending

解决方案


场景永远不会被清除,因此在新帧中将新点添加到场景中时,之前帧中绘制的点仍然存在。

说明

fill(0, 12);
rect(0, 0, width, height);

在整个视图上绘制一个透明的黑色矩形。所以前几帧的斑点似乎随着时间的推移而淡出。由于“旧”点已经被透明矩形覆盖了很多次,它们变成了深灰色。“较年轻”的斑点只被覆盖了几次,呈浅灰色。立即绘制的点是白色的,因为白色填充颜色 ( fill(255);)

如果增加混合矩形的 alpha 值,那么斑点会“消失”得更快,它们的“尾巴”会更短。

例如

fill(0, 50);

推荐阅读