java - 如何在处理中绘制指向鼠标的线
问题描述
我正在尝试制作一个程序,其中网格中的线条像磁铁一样指向鼠标。我是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);
}
解决方案
这个项目有很多解决方案。最简单的方法之一是使用 Processing 的PVector
class。
该类
PVector
可用于二维或三维向量。向量是同时具有大小和方向的实体。然而PVector
,该类存储向量的分量(x,y 表示 2D,x,y,z 表示 3D)。幅度和方向是从分量计算出来的,可以通过方法mag()
和访问heading()
。
Processing 中的二维向量通过x
和y
components定义:
PVector v = new PVector(xComponent, yComponent);
通过一些数学公式,您可以使用 x 和 y 分量来确定幅度和方向。但我们不需要确定这些。
下面,我附上了完整的解决方案代码。其中大部分内容对您来说应该是有意义的。但值得了解发生了什么PVector
。
包含表示每个网格顶点坐标的变量中的嵌套for
循环。void draw()
x
y
我们首先将定义PVector v
为一个向量,它由 的 x 分量mouseX - x
或鼠标的 x 位置与每个网格点之间的差值给出。类似地,由 给出的 y 分量mouseY - y
具有相同的差异。
创建一个从保存 aPVector u
初始化的变量,它与 具有相同的方向,但长度仅为 15。v.setMag(15)
PVector
v
现在画线。向量表示一个偏移量,而不是一个位置(在这种情况下),所以从一个网格点画一条线到一个网格点的偏移量是关键。
因此line(x, y, x + u.x, y + u.y)
,其中u.x
和u.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.
}
}
}
推荐阅读
- firebase - 是否可以在 Firebase 中仅接受来自我的应用程序的函数调用?
- c# - 如何在 c# 中使用 Linq 或 lambda 表达式获取对象的第二/第三个内部列表的总数
- iphone - 如何在 Apple 邮件客户端上调试 html 呈现问题
- kubernetes - k8s中nodePort服务如何设置固定集群端口
- ruby-on-rails - 从字符串迁移到布尔 Rails
- python - 我可以将大数字作为字符串输出到 csv
- oracle12c - 关于 Oracle DB 审计配置的说明 - 设置
- ruby - 检索 instanceProfileArn 的 Puppet Facts
- javascript - React 组件仅在某些浏览器上呈现
- php - 如何在 PHP/HTML 中更改整个页面的文本大小?