Search code examples
javagraphics2daffinetransform

Cannot understand AffineTransformation, bounding rectangle


Hi I am new to java games programming and I was reading through some code and I couldn't understand a few things. I was hoping someone here would be able to clear a few things for me.

1) I know you use "bounding rectangle" to check for collision. But my question is that when you are creating for example a polygon or square object in java from the grahpics2d/shapes classes. Do they already contain a bounding rectangle? or do we have to create it. Also what is the following the code doing, is it creating a bounding rectangle and also what information is it taking in as arguments.

public Rectangle getBounds(){
Rectangle r;
r = new Rectangle((int)getX() -6,(int) getY() -6,50,50);
return r;
}

2)I know you use something called Affine transformation to transform, rotate and scale stuff in java. But the following code is a bit confusing. Can you expelling what this code is doing:

int rotation=0;
AffineTransformation identity = new AffineTransformation();
g2d.translate(width/2, height/2);
g2d.scale(20,20);
g2d.rotate(Math.toRadians(rotation));

public void keyReleased(KeyEvent k) { }
    public void keyTyped(KeyEvent k) { }
    public void keyPressed(KeyEvent k) {
        switch (k.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            rotation--;
            if (rotation < 0) rotation = 359;
            repaint();
            break;
        case KeyEvent.VK_RIGHT:
            rotation++;
            if (rotation > 360) rotation = 0;
            repaint();
            break;
        }
    }

Now I'm mostly confused about how the if statement is processing. The rotation variable is 0 in the beginning then its decremented to -1 by (rotation--) and it checks whether -1 < 0 which it is and it then sets rotation=359 but after break does rotation goes back to 0?

And whats happening in this line:

g2d.rotate(Math.toRadians(rotation));

Is the if statement sending the value to this rotate method and that method converts it into radians and does radians are the pixels on the screen and it rotates to those pixels. Is this right?

I'll be grateful if someone can explain this to me. And please don't link me to java docs I've already read them and they have not helped me Im looking for an explanation from someone who can make it easier.

Thank you in advance.


Solution

  • Here rotation is the angle in degrees, the value is 0 <= rotation < 360

    g2d.rotate(angle) rotates an image. It requires angle to be specified in radians.

    Math.toRadians(rotation) translates degrees to radians, the value 0 <= radians < 2Pi

    Update:

    The code rotates the image when cursor keys pressed. It rotates it by 1 degree to the right or 1 degree to the left. The full turn is 360 degrees. When it reaches 360 it resets the rotation variable to zero, which is the same angle as 360. Hence :

    rotation++;
    if (rotation > 360) rotation = 0;