package animatedobjectpanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AnimatedObjectPanel extends JPanel implements ActionListener {
private int objectX = 50;
private int objectY = 50;
private int targetX = 300;
private int animationDuration = 1000; // milliseconds
private long startTime;
private Timer timer;
public AnimatedObjectPanel() {
timer = new Timer(15, this); // 15ms delay for ~60fps
timer.start();
startTime = System.currentTimeMillis();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLUE);
g2d.fillRect(objectX, objectY, 50, 50); // Draw the animated object
}
@Override
public void actionPerformed(ActionEvent e) {
long currentTime = System.currentTimeMillis();
long elapsedTime = currentTime - startTime;
if (elapsedTime < animationDuration) {
double progress = (double) elapsedTime / animationDuration;
// Apply an easing function (e.g., ease-out quadratic)
double easedProgress = 1 - Math.pow(1 - progress, 2);
objectX = (int) (50 + (targetX - 50) * easedProgress);
} else {
objectX = targetX; // Ensure it reaches the final position
timer.stop(); // Stop the timer when animation is complete
}
repaint(); // Request a redraw
}
public static void main(String[] args) {
JFrame frame = new JFrame("2D Animation with Easing");
AnimatedObjectPanel panel = new AnimatedObjectPanel();
frame.add(panel);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Tidak ada komentar:
Posting Komentar