Sprite.java
Posted in Java, on September 3, 2010 at 11:35
import java.awt.*;
import java.net.URL;
import javax.imageio.ImageIO;

public class Sprite {
    private Image img;
    private Point position;
    private Point size;

    public Sprite(String path, Point pos)
    {
	this.setImage(this.checkImage(path));
	this.setPosition(pos);
	this.setSize(new Point(img.getWidth(null), img.getHeight(null)));
    }

    public void setImage(Image image)
    {
	this.img = image;
    }

    public Image getImage()
    {
	return this.img;
    }

    public void setPosition(Point pos)
    {
	this.position = pos;
    }

    public Point getPosition()
    {
	return this.position;
    }

    public void setSize(Point Size)
    {
	this.size=Size;
    }

    public Point getSize()
    {
	return this.size;
    }

    public Image checkImage(String path)
    {
	String imgFileName = path;
        URL url = Sprite.class.getResource(imgFileName);
        Image imga = null;
        try {
            imga =  ImageIO.read(url);
        } catch (Exception e) {
        }
        return imga;
    }

    public void Move(int dx, int dy, Canvas canvas)
    {
       if(dx>=0) {
	  if(this.position.x + this.size.x + dx <= canvas.getWidth())
	     this.position.x += dx;
	  else
	     this.position.x = canvas.getWidth() - this.size.x;
       }
       else {
	  if(this.position.x + dx >= 0)
	     this.position.x += dx;
	  else
	     this.position.x = 0;
       }
       if(dy>=0) {
	  if(this.position.y + this.size.y + dy <= canvas.getHeight())
	     this.position.y += dy;
	  else
	     this.position.y = canvas.getHeight() - this.size.y;
       }
       else {
	  if(this.position.y + dy >= 0)
	     this.position.y += dy;
	  else
	     this.position.y = 0;
       }
    }

    public boolean isCollide(Sprite s2)
    {
        if((this.getPosition().y >= s2.getPosition().y &&
                s2.getPosition().y + s2.getSize().y >= this.position.y) ||
                (s2.getPosition().y >= this.getPosition().y &&
                this.getPosition().y + this.getSize().y >= s2.position.y))
        {
            if(this.getPosition().x <= s2.getPosition().x &&
                   this.getPosition().x+this.getSize().x >= s2.getPosition().x)
                return true;
            else if(this.getPosition().x >= s2.getPosition().x &&
                   s2.getPosition().x + s2.getSize().x >= this.getPosition().x)
                return true;
        }
        return false;
    }
}

Share this code

| More

Use the link below to share the code:
HTML
BBCode