Sprite Class
The BorlandBase library has a class called Sprite. A sprite is an image or graphic that moves around your screen. Mario, etc are known as sprites.
All sprites share some characteristics. They all:
- have an x and a y
- have a width and a height
They may also have:
Two ways to construct:
- super(x,y,width,height)
- super(x,y,width,height,filename) //if there is an image file
Two nice methods that are built in to Sprites are:
- drawImage(Graphics g) //if you loaded the image with super above)
- drawImage(Graphics g,String filename)
- playSound(String filename)
- isCollision(Sprite otherSprite)
To use the sprite, you will extend my class, below are two examples:
public class Paddle extends Sprite
{
//The constructor creates the paddle
public Paddle(int x)
{
super(x,100,20,75); // we are saying that the paddle will be at x of whatever they specify, y of 100, width of 20 and height of 75
}
//other methods like moveUp, moveDown, drawPaddle() will all be below.
}
And if we wanted to have a sprite with an image:
public class Mario extends Sprite
{
//The constructor creates the paddle
public Mario()
{
super(50,100,20,30, "mario.jpg"); // we are saying that the mario will be at x of 50, y of 100, width of 20 and height of 30
}
//other methods like moveUp, moveDown will all be below.
}
In our main program:
We could create a paddle (or 2 or three) by saying:
Paddle paddle1=new Paddle(600); //note Im putting a paddle at x of 600
Or mario:
Mario myMario = new Mario();
There are some really useful methods built in:
- Collision - we could see if the paddle is hitting mario:
if (paddle1.isCollision(myMario)==true) //if there is a collision
- We can automatically draw mario at its location:
myMario.drawImage(g);
|