Java 在碎砖游戏中使用atan2()查找对象的交点

Java 在碎砖游戏中使用atan2()查找对象的交点,java,trigonometry,atan2,Java,Trigonometry,Atan2,我正在看一个由r3ticuli(GitHub的用户)创建的破砖游戏的源代码。下面的方法检查两个对象是否相交,如果相交,该方法将检查并返回主对象的哪个部分被另一个对象接触 该方法是GameObject类的一部分(桨、砖和球都是该类的子类)。类对象的x和y坐标从对象的左上角开始。编写此代码的程序员只使用桨或砖调用此方法,并将球作为主方法中的参数传递 我花了两天时间来理解这个逻辑是如何工作的。我知道变量θ计算两个物体中心之间的矢量角。然而,我无法理解变量diagTheta的用途是什么,以及该方法如何确

我正在看一个由r3ticuli(GitHub的用户)创建的破砖游戏的源代码。下面的方法检查两个对象是否相交,如果相交,该方法将检查并返回主对象的哪个部分被另一个对象接触

该方法是GameObject类的一部分(桨、砖和球都是该类的子类)。类对象的x和y坐标从对象的左上角开始。编写此代码的程序员只使用桨或砖调用此方法,并将球作为主方法中的参数传递

我花了两天时间来理解这个逻辑是如何工作的。我知道变量θ计算两个物体中心之间的矢量角。然而,我无法理解变量diagTheta的用途是什么,以及该方法如何确定对象的哪一部分与另一部分相互关联

谢谢你的支持。 *如果我的问题有问题,我会解决的

/**
 * Compute whether two GameObjects intersect.
 * 
 * @param other
 *            The other game object to test for intersection with.
 * @return NONE if the objects do not intersect. Otherwise, a direction
 *         (relative to <code>this</code>) which points towards the other
 *         object.
 */
public Intersection intersects(GameObject other) {
    if (       other.x > x + width
            || other.y > y + height
            || other.x + other.width  < x
            || other.y + other.height < y)
        return Intersection.NONE;

    // compute the vector from the center of this object to the center of
    // the other
    double dx = other.x + other.width /2 - (x + width /2);
    double dy = other.y + other.height/2 - (y + height/2);

    double theta = Math.atan2(dy, dx); // In here, theta means the angle between objects. from original to the other object (center to center).
    double diagTheta = Math.atan2(height, width); // This is angle from (x,y) to its opposite tip side of the shape. 

  if ( -diagTheta <= theta && theta <= diagTheta )
        return Intersection.RIGHT;
    if ( diagTheta <= theta && theta <= Math.PI - diagTheta )
        return Intersection.DOWN;
    if ( Math.PI - diagTheta <= theta || theta <= diagTheta - Math.PI )
        return Intersection.LEFT;
    // if ( diagTheta - Math.PI <= theta && theta <= diagTheta)
    return Intersection.UP;
}
在这张图中,(dx-dy)是红色箭头,它从
这个
指向
其他
。(宽度、高度)是蓝色箭头,它是
的对角线。atan2函数将返回箭头的角度,从-pi到+pi,其中零指向右、正向上、负向下

在图中,你可以看到蓝色箭头比红色箭头更积极,也就是说它更接近圆周率。因此,θ约为2.9,θ约为2.5。这有意义吗

当您运行该逻辑时,可以看到它返回
UP
,也就是说
other
框位于
框的上方

当您将
other
框移动到不同的位置时,红色箭头将改变,您将得到不同的
theta
值。尝试几种可能性,并亲自确认逻辑返回正确的结果