Question

I'm trying to make a 2D game. I have an array of rectangles to represent attacks. I am trying to make them rotate so they are all rotated 45 degrees. When I try rendering more spells after the first, they glitch to random places around the screen. Here is my code:

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;
    }
}

And here is what is happening to my screen when I cast them all standing still:

enter image description here

They all rotate 45 more degrees every time I click to cast, but I don't know how to fix it.

Was it helpful?

Solution

Keep in mind that when you call gwb[i] = (Graphics2D) g;, you are not making a copy of g. Instead, each of your rectangles is being rotated by the cumulative sum of all of your previous rotations. Try something like this instead:

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
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top