Search code examples
javarotationgraphics2d

Java rotating and drawing with Graphics2d


    AffineTransform at;
    Graphics2D g2 = (Graphics2D)g;

    g2.setColor(Color.black);

    at = new AffineTransform();
    at.setToTranslation(x, y);
    at.setToRotation(theta);
    g2.setTransform(at);
    g2.drawPolygon(points);

My code draws a triangle at x and y... and when i press a and d the triangle rotates.. but when i press w and s, the triangle does not change its x and y.

The variables are correct.. it's the translation routine.. I'm not sure where i got wrong..

If i do this:

    AffineTransform at;
    Graphics2D g2 = (Graphics2D)g;

    g2.setColor(Color.black);

    at = new AffineTransform();
    at.setToTranslation(x, y);
    g2.setTransform(at);
    g2.drawPolygon(points);

    at.setToRotation(theta);
    g2.setTransform(at);
    g2.drawPolygon(points);

One rotates and one moves.. so why cant i apply both translations before drawing?


Solution

  •     AffineTransform at;
        Graphics2D g2 = (Graphics2D)g;
    
        g2.setColor(Color.black);
    
        at = new AffineTransform();
    
        at.translate(x, y);     
        at.rotate(theta);
        g2.setTransform(at);
        g2.drawPolygon(points);
    

    I was using the wrong things.. rotate and translate are the functions i needed.