【问题标题】:Matrix Text rain effect in Processing 3.3Processing 3.3中的矩阵文字雨效果
【发布时间】:2017-07-11 04:18:38
【问题描述】:

我正在 Processing 3.3 中制作矩阵文本雨效果,作为学习处理库和 Java 的简单入门项目。到目前为止我的代码:

class Symbol {
  int x, y;
  int switchInterval = round(random(2, 50));
  float speed;
  char value;

  Symbol(int x, int y, float speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
  }

  //Sets to random symbol based on the Katakana Unicode block
  void setToRandomSymbol() {
    if(frameCount % switchInterval == 0) {
      value = char((int) random(0x30A0, 0x3100));
    }
  }

  //rains the characters down the screen and loops them to the top when they
  // reach the bottom of the screen
  void rain() {
    if(y <= height) {
      y += speed;
    }else {
      y = 0;
    }
  }
}

Symbol symbol;

class Stream {
  int totalSymbols = round(random(5, 30));
  Symbol[] symbols = new Symbol[500];
  float speed = random(5, 20);

  //generates the symbols and adds them to the array, each symbol one symbol 
  //height above the one previous
  void generateSymbols() {
    int y = 0;
    int x = width / 2;

    for (int i = 0; i <= totalSymbols; i++) {
      symbols[i] = new Symbol(x, y, speed);
      symbols[i].setToRandomSymbol();
      y -= symbolSize;
    }
  }

  void render() {
    for(Symbol s : symbols) {
      fill(0, 255, 70);
      s.setToRandomSymbol();
      text(s.value, s.x, s.y);
      s.rain();
    }
  }
}

好的,那是很多代码,让我解释一下我的困境。我遇到的问题是,当我运行代码时,我在渲染函数的 for each 循环中的 s.setToRandomSymbol(); 方法调用处得到 NullpointerException。关于这个 NullPointerException 错误的奇怪部分和我不理解的部分是它被抛出一个不接受任何可能返回为空的参数的方法,并且该方法本身是无效的,所以它不应该什么都可以退,对吧?为什么这会返回 Null,我做错了什么让它以这种方式返回?

【问题讨论】:

  • 什么是width,你在哪里设置它?
  • width是处理库中的内置变量,等于窗口的宽度。
  • 请发帖minimal reproducible example。当我尝试运行您的代码时,我收到一个错误,因为从未定义过 symbolSize。即使我修复了那个错误,我也只是得到一个空白草图,因为你没有包含你的 setup() 或 draw() 函数。与其发布所有代码,不如尝试创建一个我们可以运行的小示例,然后我们将从那里开始。
  • 谢谢,我一定会在以后的帖子中这样做。

标签: processing


【解决方案1】:

首先你想出一个介于 5 和 30 之间的随机数:

int totalSymbols = round(random(5, 30));

然后你创建一个数组来保存你的Symbol 类的500 实例:

Symbol[] symbols = new Symbol[500];

请注意,此时此数组包含 500 个null 值。

然后将最多 30 个 Symbol 实例添加到您的数组中:

for (int i = 0; i <= totalSymbols; i++) {
  symbols[i] = new Symbol(x, y, speed);

请注意,此时此数组现在至少包含 470 个null 值。

然后你遍历所有 500 个索引:

for(Symbol s : symbols) {
  s.setToRandomSymbol();

但请记住,这些索引中至少有 470 个是 null,这就是为什么您会得到 NullPointerException。

一些基本的调试会告诉你所有这些。我会在你收到错误之前添加一个基本的println() 语句:

for(Symbol s : symbols) {
  println("s: " + s);
  s.setToRandomSymbol();

这将表明您正在迭代 null 值。

无论如何,要解决您的问题,您需要停止迭代整个数组,或者您需要停止为从未使用的索引腾出空间。

以后,请在发帖前尝试将您的问题缩小到MCVE。请注意,这个小得多的示例程序会显示您的错误:

String[] array = new String[10];
array[0] = "test";
for(String s : array){
  println(s.length());
}

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多