阵列矩形旋转

时间:2014-01-03 17:31:56

标签: java arrays rotation game-engine rectangles

我正在尝试制作2D游戏。我有一组矩形来表示攻击。我试图让它们旋转,所以它们都旋转了45度。当我尝试在第一次之后渲染更多法术时,它们会在屏幕周围出现乱码。这是我的代码:

Rectangle[] waterBolt = new Rectangle[10];
float[] wba = new float[10];
int wbc = 0;
Graphics2D[] gwb = new Graphics2D[10];

public void renderSpell(Graphics2D g) {
    for(int i=0; i<10; i++) {
        if (waterBolt[i] != null) {
            gwb[i] = (Graphics2D) g;
            gwb[i].rotate(Math.toRadian(45), waterBolt[i].x, waterBolt[i].y);
            gwb[i].fill(waterBolt[i]);
        }
    }
}

public void castSpell(int spellID) {
    waterBolt[wbc] = new Rectangle(playerX, playerY, 16, 16);
    wba[wbc] = (float) Math.toRadians(Math.atan2(mouseX - playerX, mouseY - playerY));
    wbc++;
    if (wbc >= 10) {
        wbc = 0;
    }
}

当我把它们全部静止时,屏幕上发生了什么:

enter image description here

每次点击投射时,它们都会旋转45度,但我不知道如何修复它。

1 个答案:

答案 0 :(得分:0)

请注意,当您致电gwb[i] = (Graphics2D) g;时,您并未复制g。相反,每个矩形都会被所有先前旋转的累积总和旋转。尝试这样的事情:

public void renderSpell(Graphics2D g) {
    AffineTransform transform = g.getTransform();
    for(int i=0; i<waterBolt.length; i++) {
        if (waterBolt[i] != null) {
            g.rotate(Math.toRadian(45), waterBolt[i].x, waterBolt[i].y);
            g.fill(waterBolt[i]);
            g.setTransform(transform); // back to original orientation
        }
    }
}