Java 的三角函数

Trigonometry with Java

我正在尝试用 Java 和 LibGDX 在 android 上做一些基本的三角函数。 我花了很长时间谷歌搜索 "How to find an angle in right triangles"。 我还是不太明白:(

我想给 Actor subclass 一个随机的跟随方向。那么角度是多少 - 我应该将 xSpeed 和 ySpeed 设置为多少,以便以正确的角度移动。

我开始编写一个应用程序来帮助我了解它是如何工作的。

有两个对象 - 原点和接触点。用户按下屏幕,touchPoint 移动到用户触摸的地方。方法触发以找出适当的值。我知道两点之间的 XDistance 和 YDistance。这意味着我知道相反的长度和相邻的长度。所以我需要做的就是(对面/相邻)的tan-1,对吗?

我只是不明白如何处理我的程序吐出的数字。

一些代码:

在主class的创建事件中:

stage.addListener(new ClickListener() {
         @Override
         public void touchDragged(InputEvent event, float x, float y, int pointer) {
            touchPoint.setX(x);
            touchPoint.setY(y);
            touchPoint.checkDistance(); // saves x and y distances from origin in private fields
            atan2D = getAtan2(touchPoint.getYDistance(), touchPoint.getXDistance());
            tanhD = getTanh(touchPoint.getYDistance(), touchPoint.getXDistance());
            xDistanceLbl.setText("X Distance: " + touchPoint.getXDistance());
            yDistanceLbl.setText("Y Distance: " + touchPoint.getYDistance());
            atan2Lbl.setText("Atan2: " + atan2D);
            tanhLbl.setText("Tanh: " + tanhD);
            angleLbl.setText("Angle: No idea");
         }
      })

...

private double getAtan2(float adjacent, float opposite) {
      return Math.atan2(adjacent, opposite);
   }

   private double getTanh(float adjacent, float opposite) {
      return Math.tanh((adjacent / opposite));
   }

这两个函数给出了介于 (atan2: -pi 到 pi) 和 (tanh: -1.0 到 1.0) 之间的数字

如何将这些值转换为角度,然后从中我可以向后工作并再次获得相反和相邻的角度? 这样做应该允许我创建一个随机方向的对象,我可以在 2D 游戏中使用它。

atan2 以弧度表示方向。从原点 (0,0)touchPoint 的方向。如果您需要从某个对象到 touchPoint 的方向,则减去对象坐标。也许你还想以度数来查看方向(这仅适用于人眼)

dx = x - o.x
dy = y - o.y
dir = atan2(dy, dx)
dir_in_degrees = 180 * dir / Pi

我有方向,想要检索坐标差,需要存储距离

distance = sqrt(dx*dx + dy*dy)
later
dx = distance * cos(dir) 
dy = distance * sin(dir) 

但请注意,经常存储 dxdy 会更好,因为某些计算可能会在没有三角函数的情况下执行


刚刚注意到-使用tanh是完全错误的,这是双曲正切函数,与几何无关。

你可以使用arctan,但它只给出half-range的角度(与atan2相比)