I am making a Pokemon Style 2D java game using no libraries, just pure java, and I am working on and having issues getting a water tile to animate. I want the tile to update every half a second or so. I will post my main class, abstract tile class, water class, and screen class so that maybe you can figure out a way to so me how to animate tiles in my game.
P.S: Right now I am trying to animate a water tile. And all the sprites are for testing and will be changed later.
Code at DropBox: AnimatedTile
, Main
, Screen
, Tile
.
I posted my animation tutorial in other animation question although doesn't seem the other guy liked it so much. Maybe you'll find it more useful, I used java.awt only. Has a working example on how to animate images. In my method - all of the tiles for the image to be animated are contained in one long image, and by updating the X coordinate of the part of buffer to be loaded it is possible to scroll through the frames and achieve animation that way.
Enjoy:
https://sites.google.com/site/javagamescorner/home/animated-sprites
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class AnimatedWater {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
final JPanel gui = new JPanel(new GridLayout(2,0,0,0));
final AnimatedTile[] tiles = new AnimatedTile[8];
for (int ii=0; ii<tiles.length; ii++) {
tiles[ii] = new AnimatedTile();
gui.add(new JLabel(new ImageIcon(tiles[ii])));
}
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int ii=0; ii<tiles.length; ii++) {
tiles[ii].paintImage();
gui.repaint();
}
}
};
Timer timer = new Timer(50, listener);
timer.start();
JOptionPane.showMessageDialog(null, gui);
timer.stop();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class AnimatedTile extends BufferedImage {
GradientPaint[] frameGradient;
int frame = 0;
AnimatedTile() {
super(60,60,BufferedImage.TYPE_INT_RGB);
frameGradient = new GradientPaint[6];
for (int ii=0; ii<frameGradient.length; ii++) {
frameGradient[ii] = new GradientPaint(
0f,(float)ii,Color.BLUE,
0f,(float)ii+3,Color.CYAN,true);
}
}
public void paintImage() {
Graphics2D g = createGraphics();
if (frame==frameGradient.length-1) frame = 0;
else frame++;
g.setPaint(frameGradient[frame]);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
}
}