I have attempted to write a Java sprite class. Can someone critique it for me? I feel like it has a
lot of flaws.
Sprite.java
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
/*
* Created on Nov 13, 2004
*
*/
public class Sprite extends JApplet {
int xPos;
int yPos;
private int xVelocity;
private int yVelocity;
int width;
int height;
private Image myImage;
private Box bound;
public Sprite(String filename, int myWidth, int myHeight) {
width = myWidth;
height = myHeight;
xPos = 0;
yPos = 0;
myImage = getImage(getDocumentBase(), filename);
}
public void setPosition(int newXpos, int newYpos){
xPos = newXpos;
yPos = newYpos;
}
public void processVelocity(){
xPos += xVelocity;
yPos += yVelocity;
}
public boolean collision(Sprite other){
int x0 = xPos + bound.x1;
int y0 = yPos + bound.y1;
int x1 = xPos + bound.x2;
int y1 = yPos + bound.y2;
int x2 = other.xPos + other.bound.x1;
int y2 = other.yPos + other.bound.y1;
int x3 = other.xPos + other.bound.x2;
int y3 = other.yPos + other.bound.y2;
return !(x1<x2 || x3<x0 || y1<y2 || y3<y0);
}
public void blit(Graphics g){
g.drawImage(this.myImage, xPos, yPos, width, height, this);
}
public void blit(Graphics g, int _xpos, int _ypos){
g.drawImage(this.myImage, _xpos, _ypos, width, height, this);
}
}
Box.java
[source lang = "Java"]
public class Box {
public int x1;
public int y1;
public int x2;
public int y2;
public int width;
public int height;
public Box(Sprite dude) {
x1 = dude.xPos;
y1 = dude.yPos;
x2 = x1 + dude.width;
y2 = y1 + dude.height;
width = dude.width;
height = dude.height;
}
}
Implementation.java
import java.applet.*;
import java.awt.*;
public class Implementation extends Applet
{
Sprite test;
public void init()
{
test = new Sprite("ganesha.jpg", 234, 343);
}
public void paint (Graphics g)
{
g.drawString("Hello World!", 50, 25);
}
}
I run it, and it says "Applet not initialized" and does this:
java.lang.NullPointerException
at java.applet.Applet.getDocumentBase(Unknown Source)
at Sprite.<init>(Sprite.java:26)
at Implementation.init(Implementation.java:9)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at java.applet.Applet.getDocumentBase(Unknown Source)
at Sprite.<init>(Sprite.java:26)
at Implementation.init(Implementation.java:9)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
What could be going wrong? I have the ganesha.jpg in the right place.
[Edited by - CodeTitan on November 13, 2004 5:15:03 PM]