有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java仅为一个函数使用后台

我正在制作一部关于processing的动画。然后,我有一个关于代码的问题。通常,我的代码比较长。然而,我做了一个简单的代码,它也可以对初学者有用。我的示例代码:

int x1 = 0;
int x2 = 0;

void setup() {
  size(500, 100); // create a screen
}

void draw() {
  background(255);
  drawRectangle();
  drawPoint();
}

void drawRectangle() {
  rect(x1, 20, 20, 20); // rect(x, y, width,height);
  x1 +=5;
}

void drawPoint() {
  point(x2, 20); // point(x, y);
  x2++;
}

所以,我有点和矩形在同一个方向上。{}对这两者都有影响。但是,背景不应影响这些要点。因为我想用点画一条线。背景应该只影响矩形。 解决方案应该如下所示: enter image description here


共 (1) 个答案

  1. # 1 楼答案

    你会想用一种更简单的方法来解决这个问题。与其画一条有多个点的线,不如画一条实际的线!你也只能使用1x

    这是一个小示例程序,它生成以下输出:

    int x = 10, y = 50;
    
    void setup() {
      size(400, 400);
      rectMode(CENTER); // So the values you give rect() are seen as the center of the rectangle
    }
    
    void draw() {
      background(255);
    
      drawLine();
      drawRectangle();
    
      x += 3;
    }
    
    void drawLine() {
      strokeWeight(5); // Make the line more visible
      line(0, y, x, y); // Draw a line from the left of the screen to x
      strokeWeight(1); // Return to standard
    }
    
    void drawRectangle() {
      fill(255, 0, 0); // Make the color red
      rect(x, y, 20, 20); // Draw the rectangle
    }
    

    An example