Question 1: How should I structure my project so the sound and images files can be loaded most easily? Right now, I have the folder:
C:\java\pacman
with the sub-directory
C:\java\pacman\src
containing all the code, and
C:\java\pacman\assets
containing the images and .wav files. Is this the best structure or should I put the assets somewhere else?
Question 2:
What's the best way to refer to the images/sounds without using the full path e.g C:\java\pacman\assets\something.png
to them? If I use the getCodeBase()
function it seems to refer to the C:\java\pacman\bin
instead of C:\java\pacman\
.
I want to use such a function/class which would work automatically when i compile the applet in a jar as well as right now when I test the applet through eclipse.
Question 3: How should I load the images/sounds? This is what I'm using now:
1) For general images:
import java.awt.Image;
public Image getImg(String file)
{
//imgDir in this case is a hardcoded string containing
//"C:\\java\\pacman\\assets\\"
file=imgDir + file;
return new ImageIcon(file).getImage();
}
The images returned from this function are used in the drawImage
method of the Graphics
class in the paint
method of the applet.
2) For a buffered image, which is used to get subImages and load sprites from a sprite sheet:
public BufferedImage getSheet() throws IOException
{
return ImageIO.read(new File(img.getPath("pacman-sprites.png")));
}
Later:
public void loadSprites()
{
BufferedImage sheet;
try
{
sheet=getSheet();
redGhost.setNormalImg(sheet.getSubimage(0, 60, 20, 20));
redGhost.setUpImg(sheet.getSubimage(0, 60, 20, 20));
redGhost.setDownImg(sheet.getSubimage(30, 60, 20, 20));
redGhost.setLeftImg(sheet.getSubimage(30, 60, 20, 20));
redGhost.setRightImg(sheet.getSubimage(60, 60, 20, 20));
}
catch (IOException e)
{
System.out.println("Couldnt open file!");
System.out.println(e.getLocalizedMessage());
}
}
3) For sound files:
import sun.audio.*;
import java.io.*;
public synchronized void play() {
try {
InputStream in = new FileInputStream(filename);
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
} catch (IOException e) {
e.printStackTrace();
}
}