从固定点 50px 向鼠标位置绘制直线 Java

发布于 2024-10-31 10:35:51 字数 260 浏览 2 评论 0原文

我想根据鼠标的位置从一个固定点到一个点画一条长度为 50px 的线,但我对三角学很糟糕。 我一整天都被困在这个问题上,但仍然不知道该怎么做。 使用的四个变量是:

startX; //X position of fixed point
startY; //Y position of fixed point
mouseX; //X position of mouse
mouseY; //Y position of mouse

提前致谢。

I am trying to draw a line which is 50px in length from a fixed point to a point based on the position of the mouse but I am terrible at trigonometry.
I have been stuck on this all day and still have no idea how to do it.
the four variables used are:

startX; //X position of fixed point
startY; //Y position of fixed point
mouseX; //X position of mouse
mouseY; //Y position of mouse

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

§对你不离不弃 2024-11-07 10:35:51

您需要在鼠标光标到该点。然后将单位向量乘以 50,就得到了该方向长度为 50 的向量。

因此,您首先获得从固定点到鼠标光标的向量:

float dirX = mouseX - startX;
float dirY = mouseY - startY;

然后对该向量进行归一化(使其长度为 1)

float dirLen = sqrt(dirX * dirX + dirY * dirY); // The length of dir
dirX = dirX / dirLen;
dirY = dirY / dirLen;

现在我们将归一化向量乘以 50,我们就得到了我们想要的方向上长度为 50 的向量。

float lineX = dirX_normalized * 50;
float lineY = dirY_normalized * 50;

现在我们可以画线了

g.drawLine(startX, startY, startX + lineX, startY + lineY);

You'll want to make a Unit Vector (a vector with length 1) in the direction of the mouse cursor to the point. Then you multiply the unit vector by 50 and you've got a vector of length 50 in that direction.

So you first get the vector from the fixed point to the mouse cursor:

float dirX = mouseX - startX;
float dirY = mouseY - startY;

Then your normalize this vector (make it's length 1)

float dirLen = sqrt(dirX * dirX + dirY * dirY); // The length of dir
dirX = dirX / dirLen;
dirY = dirY / dirLen;

Now we multiply the normalized vector by 50 and we've got a vector of length 50 in the direction we want.

float lineX = dirX_normalized * 50;
float lineY = dirY_normalized * 50;

Now we can draw our line

g.drawLine(startX, startY, startX + lineX, startY + lineY);
椒妓 2024-11-07 10:35:51

假设您使用 AWT Graphics class,你可以这样做:

double angle=Math.atan2(mouseY-startY, mouseX-startX);
g.setColor(Color.BLACK);
g.drawLine(startX, startY,
    Math.floor(startX+Math.cos(angle)*50),
    Math.floor(startY+Math.sin(angle)*50));

Assuming you're using the AWT Graphics class, you could do this:

double angle=Math.atan2(mouseY-startY, mouseX-startX);
g.setColor(Color.BLACK);
g.drawLine(startX, startY,
    Math.floor(startX+Math.cos(angle)*50),
    Math.floor(startY+Math.sin(angle)*50));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文