【问题标题】:Calculate Angle for OpenGL Rotation计算 OpenGL 旋转的角度
【发布时间】:2015-04-18 23:49:48
【问题描述】:

我在计算这个角度时遇到了一点麻烦,我希望你们中的一位天才可以帮助我。

我有一个带有大炮的游戏,它可以在游戏世界的任何位置。使用 OpenGL 的矩阵变换,我希望大炮的纹理能够旋转以朝向玩家放置手指的任何方向。为此,我需要计算一个角度以发送到旋转矩阵。

目前我在正确计算角度时遇到了一点问题。

见图:

图例: A) 始终指向屏幕顶部的恒定单位向量。 B) 基于用户点击屏幕的位置设置的点。 theta) 我需要测量的角度

如您所见,我使用的是始终指向上方的恒定单位向量作为基线 (A)。我的算法需要做的是正确测量 A 和 B 之间的角度(θ)。

这是设置目标位置的代码:

    public void setTarget(Vector2 targetPos) {

    //calculate target's position relative to cannon
    targetPos = sub(targetPos, this.position);

    //replace target
    this.target = targetPos;

    //calculate new angle
    //This is broken
    this.cannonAngle = findAngleBetweenTwoVectors(POINT_UP, target);

“findAngleBetweenTwoVectors”方法似乎不起作用。代码在这里:

 public static float findAngleBetweenTwoVectors(Vector2 baseVec, Vector2 newVec) {

    //first, make copies of the vectors
    Vector2 baseCopy = new Vector2(baseVec);
    Vector2 newCopy = new Vector2(newVec);

    //next, ensure they're normalized
    baseCopy.nor();
    newCopy.nor();

    //the arc-cosine is the angle between the two vectors
    //this is used as the "cannonAngle" value (does not work)

    return (float) Math.acos(newCopy.dot(baseCopy));
}

我知道这可能是一个矢量数学问题,但我似乎无法正确计算角度。

提前感谢您的帮助。

【问题讨论】:

  • 您的向量数学看起来是正确的,但Math.acos 方法返回的值以弧度表示。如果这是您想要的,那么我不确定出了什么问题。
  • 非常相似的问题在这里stackoverflow.com/a/28427322/2521214

标签: java opengl math rotation vector-graphics


【解决方案1】:

获取 B 的坐标并从中减去大炮的坐标,得到一个指向所需方向的向量。 Java atan2 函数可用于获取向量的弧度角度。要获得相对于向上向量的角度,顺时针方向,将参数以 x,y 而不是 y,x 的顺序传递给 atan2(这会给出从右指向向量逆时针方向的结果)。

所以你需要这样的东西:

double dx = b_x - cannon_x;
double dy = b_y - cannon_y;
double angle_in_degrees = Math.toDegrees(Math.atan2(dx,dy));

这个答案假设 A 向量指向上方,如你所说,因此是 (0,1)。如果 A 向量是任意的,那么您的原始答案看起来几乎是正确的,但您需要转换为评论者所说的度数,并且可能还要检查您的答案是顺时针还是逆时针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多