【问题标题】:Get the coordinates at the edge of the screen from a given angle从给定角度获取屏幕边缘的坐标
【发布时间】:2015-08-15 23:46:02
【问题描述】:

我知道起点(屏幕中间)和角度(在我的示例中为 20°)。现在我想知道屏幕边缘的位置,就像在给定角度从中心到边缘绘制一条不可见的线。为了更好地解释,我附上了一张图片:

【问题讨论】:

  • 我猜你只需要知道屏幕的大小,不是吗(以及你已知点的绝对坐标)?
  • 我可以用getHeight()getWidth()得到高度和宽度,所以我已知点的y是height / 2,x是width / 2
  • 未知点在 x = 0,确定 y 只是使用角度的几何问题。这个几何问题是你的问题吗?
  • 如果我的角度是 130°,我怎么知道 x 还是 y 应该是 0?

标签: java math coordinates


【解决方案1】:

一种方法是在半径等于或大于最大对角线的圆上计算一个点,然后将其裁剪到屏幕边界。

利用毕达哥拉斯定理,最大对角线的长度为

float d = Math.sqrt((width/2)*(width/2) + (height/2)*(height/2));

所以你可以像这样计算圆上的点(角度从顶部顺时针以弧度表示):

float x = Math.sin(angle) * d;
float y = -Math.cos(angle) * d;

然后您必须将向量从原点剪辑到 4 边中的每一边,例如右侧和左侧:

if(x > width/2)
{
    float clipFraction = (width/2) / x; // amount to shorten the vector
    x *= clipFraction;
    y *= clipFraction;
}
else if(x < -width/2)
{
    float clipFraction = (-width/2) / x; // amount to shorten the vector
    x *= clipFraction;
    y *= clipFraction;
}

对 height/2 和 -height/2 也执行此操作。然后最后你可以在 x 和 y 上添加 width/2, height/2 以获得最终位置(屏幕中心为 width/2,height/2 不是 0,0):

x += width/2
y += height/2

【讨论】:

  • 我想这也解释了它:stackoverflow.com/questions/3536428/…
  • 我试过了,但我认为我做错了,因为它不起作用。我将代码粘贴到问题中。
  • 您只需要检查您的减号和比较运算符是否正确。我已经编辑了答案以显示 -width/2 的剪辑
  • 您使用角度还是弧度?您可以使用 Math.toRadians(angle) 转换为弧度。还使用 sin 表示 x 和 -cos 表示 y 从顶部顺时针移动
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多