I have spent the past week trying to convert my code but without success. To be honest, I don't have that much experience in java, and this thing is giving me a headache. I am totally confused.
below is a simple animation code in passive rendering (similar to the code that I use in my game). Can you please help me to convert it to active rendering. If you have the time to help me with this, then I am sure I will be able to do it for the rest of my game. I hope I'm not asking for too much.
Thanx
The below code uses 7 GIF images for pacman animation.
-----------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class PacmanM extends JPanel implements ActionListener { private ImageIcon images[]; private static final int TOTAL_IMAGES=7, ANIM_DELAY=50; private int currentImage = 0; private Timer animationTimer; private int delay = 0;
public PacmanM(int delay) { this.delay = delay; setupAnimation(); } public PacmanM() { setupAnimation(); } public void setupAnimation() { this.setSize(this.getPreferredSize()); this.images = new ImageIcon[TOTAL_IMAGES];
for (int i = 0; i < images.length; i++) { images[i] = new ImageIcon("pac"+i+".gif"); } startAnimation(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.fillRect(0,0,this.getWidth(), this.getHeight()); if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE) { images[currentImage].paintIcon(this, g, 0, 0); currentImage = (++currentImage) % TOTAL_IMAGES; } } public void startAnimation() { if (animationTimer == null) { currentImage = 0; animationTimer = new Timer( ANIM_DELAY + delay, this); animationTimer.start(); } else { if (!animationTimer.isRunning()) animationTimer.restart(); } } public void stopAnimation (){ animationTimer.stop(); } public void actionPerformed(ActionEvent e){ repaint(); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize (){return new Dimension(400,400);} public static void main(String[] args ) { PacmanM PacMan = new PacmanM(); JFrame main = new JFrame("PacMan"); main.getContentPane().add(PacMan, BorderLayout.CENTER); main.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); main.pack(); main.show(); } } |