首页 > 解决方案 > 如何在处理中绘制指向鼠标的线

问题描述

我正在尝试制作一个程序,其中网格中的线条像磁铁一样指向鼠标。我是Processing的初学者,有人可以指点我如何做到这一点的教程或给我一些代码并解释它的作用吗?

int x1 = 0;
int x2 = 0;
int y1 = 0;
int y2 = 0;

void setup() {
  size(200, 200);
}

void draw() {
  background(255, 255, 0);
  x1 = (mouseX + 100) / 2;
  y1 = (mouseY + 100) / 2;
  x2 = -1 * x1 + 200;
  y2 = -1 * y1 + 200;
  line(x1, y1, x2, y2);
}

标签: javaprocessing

解决方案


这个项目有很多解决方案。最简单的方法之一是使用 Processing 的PVectorclass

该类PVector可用于二维或三维向量。向量是同时具有大小方向的实体。然而PVector,该类存储向量的分量(x,y 表示 2D,x,y,z 表示 3D)。幅度和方向是从分量计算出来的,可以通过方法mag()和访问heading()

Processing 中的二维向量通过xy components定义:

PVector v = new PVector(xComponent, yComponent);

通过一些数学公式,您可以使用 x 和 y 分量来确定幅度和方向。但我们不需要确定这些。

下面,我附上了完整的解决方案代码。其中大部分内容对您来说应该是有意义的。但值得了解发生了什么PVector

包含表示每个网格顶点坐标的变量中的嵌套for循环。void draw()xy

我们首先将定义PVector v为一个向量,它由 的 x 分量mouseX - x或鼠标的 x 位置与每个网格点之间的差值给出。类似地,由 给出的 y 分量mouseY - y具有相同的差异。

创建一个从保存 aPVector u初始化的变量,它与 具有相同的方向,但长度仅为 15。v.setMag(15)PVectorv

现在画线。向量表示一个偏移量,而不是一个位置(在这种情况下),所以从一个网格点画一条线到一个网格点的偏移量是关键。

因此line(x, y, x + u.x, y + u.y),其中u.xu.y是向量 的 x 和 y 分量u


void setup() {
  size(600, 600); // Set the size of the canvas to 600x600.
}

void draw() {
  background(255);
  stroke(200); // Set the stroke color to black

  int distVertLine = width / 10; // This variable defines the distance between each subsequent vertical line.
  for(int i = 0; i < width; i += distVertLine) {
    line(i, 0, i, height); // Draw a line at x=i starting at the top of the canvas (y=0) and going to the bottom (y=height)
  }

  int distHorizLine = height / 10; // This variable defines the distance between each subsequent vertical line.
  for(int i = 0; i < width; i += distHorizLine) {
    line(0, i, width, i); // Draw a line at y=i starting at the left of the canvas (x=0) and going to the right (x=width)
  }

  stroke(0); // Set the stroke to black.

  // Use a nested for loop to iterate through all grid vertices.
  for(int x = 0; x <= width; x += width/10) {
    for(int y = 0; y <= height; y += height/10) {
      PVector v = new PVector(mouseX - x, mouseY - y); // Define a vector that points in the direction of the mouse from each grid point.
      PVector u = v.setMag(15); // Make the vector have a length of 15 units.

      line(x, y, x + u.x, y + u.y); // Draw a line from the grid vertex to the terminal point given by the vector.
    }
  }
}

显示固定长度线的草图的屏幕截图。


推荐阅读