Java - 围绕其中心旋转多边形

时间:2014-03-16 07:45:24

标签: java graphics geometry 2d game-engine

我试图根据给定的theta变量围绕自己的中心点旋转多边形。它似乎有点工作,但有一些大问题。它以越来越快的速度旋转,我不明白。 Polygon本身在旋转时尺寸也会缩小,直到这些点相互移动为止。

这是我的代码的主要旋转部分。

public void Rotate(double dTheta)
{
    this.theta += dTheta;

    for(int i = 0; i < body.npoints; i++)
    {
        body.xpoints[i] = 
                (int) (body.getBounds2D().getCenterX() + (body.xpoints[i] - body.getBounds2D().getCenterX()) * 
                        Math.cos(theta) - (body.ypoints[i] - body.getBounds2D().getCenterY()) * Math.sin(theta));

        body.ypoints[i] = 
                (int) (body.getBounds2D().getCenterY() + (body.xpoints[i] - body.getBounds2D().getCenterX()) * 
                        Math.sin(theta) + (body.ypoints[i] - body.getBounds2D().getCenterY()) * Math.cos(theta));
    }
}

'body'对象是一个Polygon,每帧以60 FPS的速率绘制。

当用户按下空格键时,theta变量增加Math.PI / 180因子。

我使用的相当大的数学运算是我在网上找到的东西,它应该根据弧度角和锚点旋转一个点。

'body'多边形本身由点(-16,0),(16,-16)和(16,16)组成。 “body”Polygon最初放置在位置(100,100)处,除旋转外不会从那里平移。

我非常感谢有关此主题的任何帮助,请提前感谢。

2 个答案:

答案 0 :(得分:0)

好的,所以当我从一个不好的角度解决问题时,我觉得有点无能为力,请求帮助。

我通过将原始多边形的点存储在两个名为xpoints和ypoints的int数组中来解决我的问题。一旦加载,这些点将永远不会改变,它们与多边形的位置无关,而是与多边形中心周围的点的位置有关,这些点在任何给定时刻都可以改变。

我所做的是在每帧中循环遍历所有这些点,并使用AffineTransform类以(0,0)为中心获取每个点的旋转实例。然后我从这些旋转点中构造出一个Polygon对象,并根据玩家的x和y位置(我班上存储的变量)对其进行翻译。

这是我使用的代码段。

public void DoFrame(Graphics2D g)
{
    // Increment x by the dx factor
    x += dx * game.GetDeltaTime();
    // Increment y by the dy factor
    y += dy * game.GetDeltaTime();

    // Reset the body polygon
    body.reset();
    // Loop through all of the reference polygon points
    for(int i = 0; i < xpoints.length; i++)
    {
        // Create a placeholder array for the two points
        double[] pt = {xpoints[i], ypoints[i]};
        // Rotate the points around a center (0, 0)
        AffineTransform.getRotateInstance(theta, 0, 0).transform(pt, 0, pt, 0, 1);
        // Add the rotated point to the body
        body.addPoint((int) pt[0], (int) pt[1]);
    }
    // Translate the body based on x and y coordinates
    body.translate((int) x, (int) y);
}

这将粗略地显示基于原始传递点的中心的旋转多边形,但请注意,所使用的中心不是完美的中心,而是取决于构造函数调用时点的位置。

答案 1 :(得分:0)

您没有按照您的想法应用旋转变换。因为您首先修改x并使用修改后的值来计算y。保存x

的副本
相关问题