首页 > 解决方案 > Java 三角函数

问题描述

我正在尝试在 android 上使用 Java 和 LibGDX 做一些基本的三角函数。我花了很长时间在谷歌上搜索“如何在直角三角形中找到一个角度”。我还是不太明白:(

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

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

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

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

一些代码:

在主类的创建事件中:

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 to pi) 和 (tanh: -1.0 to 1.0) 之间的数字

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

标签: javaandroidmathlibgdxtrigonometry

解决方案


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,但它仅给出半范围内的角度(与 相比atan2


推荐阅读