旋转所有矩形角

Rotating all rectangle corners

我正在开发一款你是宇宙飞船的游戏。这艘宇宙飞船必须能够旋转。矩形有两个数组 x[], y[] 包含矩形的所有角点位置。但是当我应用旋转公式时,我得到了一个相当奇怪的旋转。试着解释一下,它看起来像是在旋转屏幕的左下角。

为了制作这些角阵列,我采用了 x 位置、y 位置、宽度和高度。

角阵列的制作

public Vertex2f(float x, float y, float w, float h){
    this.x[0] = x; 
    this.y[0] = y;

    this.x[1] = x+w;
    this.y[1] = y;

    this.x[2] = x+w;
    this.y[2] = y+h;

    this.x[3] = x;
    this.y[3] = y+h;
}

我的旋转功能

public void rotate(float angle){
    this.rotation = angle;

    double cos = Math.cos(rotation);
    double sin = Math.sin(rotation);

    for(int i = 0; i < x.length; i++){
        x[i] = (float)(cos * x[i] - sin * y[i]);
        y[i] = (float)(sin * x[i] + cos * y[i]);

    }

}

如果有帮助,我在 java 中对所有图形使用 LWJGL/OpenGL,并使用 Slick2d 加载和初始化我正在使用的精灵。

试试这个:

public void rotate(float angle){
    this.rotation = angle;

    double cos = Math.cos(rotation);
    double sin = Math.sin(rotation);

    double xOffset = (x[0]+x[2])/2;
    double yOffset = (y[0]+y[2])/2;

    for(int i = 0; i < 3; i++){
        x[i] = (float)(cos * (x[i]-xOffset) - sin * (y[i]-yOffset)) + xOffset;
        y[i] = (float)(sin * (x[i]-xOffset) + cos * (y[i]-yOffset)) + yOffset;

    }

}

您必须围绕矩形的中心旋转。否则中心在 x=0 和 y=0

已编辑:

public void rotate(float angle){
    this.rotation = angle;

    double cos = Math.cos(rotation);
    double sin = Math.sin(rotation);

    double xOffset = (x[0]+x[2])/2;
    double yOffset = (y[0]+y[2])/2;

    for(int i = 0; i < 3; i++){
        double newX = (float)(cos * (x[i]-xOffset) - sin * (y[i]-yOffset)) + xOffset;
        double newY = (float)(sin * (x[i]-xOffset) + cos * (y[i]-yOffset)) + yOffset;

        x[i] = newX;
        y[i] = newY;
    }
}

other thread

公式有问题

    x[i] = (float)(cos * x[i] - sin * y[i]);
    y[i] = (float)(sin * x[i] + cos * y[i]);

除了缺少旋转中心之外,您还更改了第一个公式中的 x[i],但希望在第二个公式中使用原始值。因此你需要使用局部变量 lx, ly

    float lx = x[i] - xcenter;
    float ly = y[i] - ycenter;
    x[i] = xcenter + (float)(cos * lx - sin * ly);
    y[i] = ycenter + (float)(sin * lx + cos * ly);

如果对象已经旋转 rotation 的角度,则此代码将角度 angle 添加到总旋转角度。相反,如果给定参数 angle 是新的总旋转角度,则需要使用角度差计算 sincos 值。也就是说,开始程序,例如,

public void rotate(float angle){


    double cos = Math.cos(angle - rotation);
    double sin = Math.sin(angle - rotation);

    this.rotation = angle;