沿已知角度画一条已知距离的线
我知道这不是一个很难的三角问题,但遗憾的是我数学迟钝。
我需要从已知起点沿已知角度到未知终点绘制一条 50 像素的线。该角度是从起点 (400,400) 和鼠标单击得出的;需要向鼠标单击方向绘制线条,但仅向单击方向绘制 50 像素。
我在谷歌上进行了广泛的搜索并找到了许多解决方案,但它对我来说并不合适。
这是我获取角度的方法:
float angle = (float) Math.toDegrees(Math.atan2(400 - event.getY(), 400 - event.getX()));
float angleInDegrees = (angle + 270) % 360;
“事件”是鼠标单击。
float endX = 250 + 50 * (float)Math.cos(angleInDegrees);
float endY 250 + 50 * (float)Math.sin(angleInDegrees);
line.setStartX(400);
line.setStartY(400);
line.setEndX(endX);
line.setEndY(endY);
我发现的所有内容都围绕 Math.cos 和 Math.sin 但我仍然不明白。我认为这个问题与将弧度映射到场景坐标有关,但我不确定。那么各位,我到底哪里蠢了?我将不胜感激任何帮助。
I know this isn't a hard trig issue, but sadly I am math retarded.
I need to draw a line of 50 pixels from a known starting point along a known angle to an unknown ending point. The angle is derived from a starting point (400,400) and a mouse click; the line needs to be drawn towards the mouse click, but only 50 pixels towards the click.
I've google'd extensively and found a number of solutions, but it's just not coming together for me.
Here is how I'm getting the angle.:
float angle = (float) Math.toDegrees(Math.atan2(400 - event.getY(), 400 - event.getX()));
float angleInDegrees = (angle + 270) % 360;
"event" is a mouse click.
float endX = 250 + 50 * (float)Math.cos(angleInDegrees);
float endY 250 + 50 * (float)Math.sin(angleInDegrees);
line.setStartX(400);
line.setStartY(400);
line.setEndX(endX);
line.setEndY(endY);
Everything I've found revolved around Math.cos and Math.sin but I'm still not getting it. I think the issue is related to mapping radians to scene coordinates, but I'm not sure. So people, in what way am I stupid? I'd appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不会为角度而烦恼。您只需使用比率即可做到这一点:
然后从 (startX, startY) 绘制到 (endX, endY)。
事情是这样的:
I wouldn't bother with angles. You can do this just using ratios:
Then draw from (startX, startY) to (endX, endY).
Here's what's going on:
您甚至不必处理弧度/度数。回到正弦和余弦的几何定义:正弦是
对边/斜边
,余弦是邻边/斜边
。 (“对边”和“相邻”是指直角三角形的边分别与您要计算正弦或余弦的角度相对和相邻)。所以:
You don't even have to deal with radians/degrees. Go back to the geometrical definition of sine and cosine: sine is
opposite/hypotenuse
, cosine isadjacent/hypotenuse
. ("Opposite" and "adjacent" mean the legs of the right triangle respectively opposite and adjacent to the angle you're taking the sine or cosine of).So:
代码中的错误是您使用了度数,而
Math.cos
和Math.sin
需要 弧度。使用
Math.toRadians
而不是Math.toDegrees
,您的代码将开始工作。Error in your code is that you using degrees, while
Math.cos
andMath.sin
requires argument in radians.Use
Math.toRadians
instead ofMath.toDegrees
and your code will start to work.