Welcome to Computer Programming

 

Sprite Class

 

BorlandBase 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:

  • an image

There are some nice methods that are built in to Sprites:

  • 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 and we will call setupSprite:


public class Paddle extends Sprite
{

    //This is You can automatically setup the x,y,width and height using below:The constructor creates the paddle
    public void setup()
    {
		setupSprite(40,100,20,75); // we are saying that the paddle will be at x of 40, 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 setup()
    {
		setupSprite(50,100,20,30);
		setupImage("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();

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 or paddle at its location:

myMario.drawImage(g);

  • We can get the x and y (and width/height) like before

myMario.x or myMario.width