我正在尝试制作一个程序,其中网格中的线条像磁铁一样指向鼠标。我是处理领域的初学者,有人可以向我指出如何执行此操作的教程,或者给我一些代码并解释它的作用吗?
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);
}
最佳答案
这个项目有很多解决方案。最简单的方法之一是使用处理的 PVector
class .
The
PVector
class can be used for two or three dimensional vectors. A vector is an entity that has both magnitude and direction. ThePVector
class, however, stores the components of the vector (x,y for 2D, and x,y,z for 3D). The magnitude and direction are calculated from the components and can be accessed via the methodsmag()
andheading()
.
Processing 中的二维 vector 是通过 x
定义的。和y
组件:
PVector v = new PVector(xComponent, yComponent);
通过一些数学公式,您可以使用 x 和 y 分量确定幅度和方向。但我们不需要确定这些。
下面,我附上了完整的解决方案代码。其中大部分内容对您来说应该是有意义的。但值得了解 PVector
发生了什么.
嵌套for
在 void draw()
内循环包含x
和y
表示每个网格顶点坐标的变量。
我们首先定义PVector v
作为 mouseX - x
的 x 分量给出的 vector ,或鼠标的 x 位置与每个网格点之间的差值。类似地,mouseY - y
给出的 y 分量具有相同的差异。
创建变量 PVector u
从 v.setMag(15)
初始化持有PVector
与 v
具有相同的方向 ,但长度仅为 15。
现在画线。 vector 表示偏移,而不是位置(在本例中),因此从网格点到网格点的偏移绘制一条线是关键。
因此line(x, y, x + u.x, y + u.y)
,其中u.x
和u.y
是 vector u
的 x 和 y 分量.
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.
}
}
}
关于java - 如何在处理中绘制指向鼠标的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630871/