JavaMan111
JavaMan111

Reputation: 35

Java Rotation Animation

Programming language: Java

Ok, so I want to have a BufferedImage that keeps rotating infinitely. I'm still pretty new at asking good question, so do bear with me.

I have a BufferedImage called arm and it is rectangular and I have an ActionListener that loops repaint() every 100 milliseconds my code is:

public void paint(Graphics g){ 
    AffineTransform t = new AffineTransform(); 
    t.rotate(Math.toRadians(90),(a­­rm.getWidth()/2)*scale,0); 
    t.translate(300,300); 
    g.drawImage(arm,t,null);
}

If you're wondering I resized the image 4x bigger so the variable scale = 4. I think my error is that I'm not mapping the pivot-point correctly but I have no idea. I really need this for my game so please help I am sooooo desperate right now.

Upvotes: 1

Views: 4628

Answers (1)

Gene
Gene

Reputation: 46960

A new AffineTransform always has zero rotation. You are adding a 90-degree rotation, so every frame of your animation will look the same: the image rotated 90 degrees from its normal orientation.

You need to calculate the current rotation angle.

// Instance variable intialized at zero.
double angle = 0.0;

// In your ActionListener timer handler increment the angle.
{
    angle += Math.toRadians(5); // 5 degrees per 100 ms = 50 degrees/second
    while (angle > 2 * Math.pi()) 
        angle -= 2 * Math.pi();  // keep angle in reasonable range.
}

public void paint(Graphics g) {
    // Just use the transform that's already in the graphics.
    Graphics2d g2 = (Graphics2d) g;
    g2.setToIdentity();
    // The code for your other transforms is garbled in my browser. Fill in here.
    g2.rotate(angle);
    g2.drawImage(arm, t, null);
}  

Hope this gets you closer.

I'll add that 100 ms is pretty slow for a frame rate. The animation will look jerky. Smooth action needs at most 30 ms or 30 frames per second. Games that use the GPU sometimes run over 100 fps.

And you should avoid new when possible inside the animation loop. It will require the garbage collector to run more frequently. This can cause a stutter in the animation.

Upvotes: 2

Related Questions