I am still in the process of learning how to animate images more efficiently on the screen. I want to bring my monster to life after seeing the monster move up and down statically for 2 months.
My thought process on animating the monster is to use a dynamic array like an ArrayList. While the animation looks correct on screen, the monster certainly moves like the monsters from the Mario game on NES. But I don't think the code implementation below is the way most people would do it most commonly.
The image frames below are stored in an ArrayList of Images manually.
The Ghost uses 3 separate image frames of animation(meaning it is not using a sprite sheet for a simplistic learning experience)
The code draws a different images depending on what position the monster is on the screen. Once the position has been reached, the game draws a new image. The way the monster gets a new image is by using the get method while providing a hard-coded index argument of the image elements from the ArrayList of Images.
public class Ghost extends Sprite {
private Image image;
private ArrayList<Image> arrayListOfImages;
public Ghost(double x, double y) {
// TODO Auto-generated constructor stub
position = new Vector2D(x,y);
velocity = new Vector2D();
arrayListOfImages = new ArrayList<Image>();
try
{
image = ImageIO.read(new File("src/Ghost/Ghost1.PNG"));
arrayListOfImages.add(image);
image = ImageIO.read(new File("src/Ghost/Ghost2.PNG"));
arrayListOfImages.add(image);
image = ImageIO.read(new File("src/Ghost/Ghost3.PNG"));
arrayListOfImages.add(image);
}
catch (IOException e) {
e.printStackTrace();
}
}
public void draw(Graphics g) {
// Draw the monster image at our position
if(position.y >= 0)
{
g.drawImage(arrayListOfImages.get(0), (int)position.x, (int)position.y, null);
}
if(position.y >= 50)
{
g.drawImage(arrayListOfImages.get(1), (int)position.x, (int)position.y, null);
}
if(position.y >= 100)
{
g.drawImage(arrayListOfImages.get(2), (int)position.x, (int)position.y, null);
}
}
}