从固定点 50px 向鼠标位置绘制直线 Java
我想根据鼠标的位置从一个固定点到一个点画一条长度为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在鼠标光标到该点。然后将单位向量乘以 50,就得到了该方向长度为 50 的向量。
因此,您首先获得从固定点到鼠标光标的向量:
然后对该向量进行归一化(使其长度为 1)
现在我们将归一化向量乘以 50,我们就得到了我们想要的方向上长度为 50 的向量。
现在我们可以画线了
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:
Then your normalize this vector (make it's length 1)
Now we multiply the normalized vector by 50 and we've got a vector of length 50 in the direction we want.
Now we can draw our line
假设您使用 AWT
Graphics class
,你可以这样做:
Assuming you're using the AWT
Graphics
class, you could do this: