用矩形检查图像的交点

时间:2014-10-10 15:10:27

标签: java user-interface rectangles

因此,我被指示:"通过实现"重叠"来修改Sprite类。函数返回true如果作为参数传入的Sprite的任何部分与当前Sprite重叠。您将需要使用x和y坐标以及Sprite的大小。"

我被建议使用矩形来完成这项工作并检查交叉点。但是,我不确定我所拥有的是正确的方法:(它在布尔重叠方法中实现)

一如既往,非常感谢您的时间。

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.imageio.ImageIO;

import java.io.File;
import java.io.IOException;
import java.util.Random;

abstract class Sprite
{
    private int x;
    private int y;
    private int size;
    private int w;
    private int h;
    private int xSlope;
    private int ySlope;
    private Image image;
    private static Random rand;

    public Sprite(int xIn, int yIn, int width, int height, String imagePath, int imageSize) {
        if (rand == null) {
            rand = new Random();
        }
        size = imageSize;
        setImage(imagePath);
        x = xIn;
        y = yIn;
        w = width;
        h = height;
        xSlope = rand.nextInt(11) - 5;
        ySlope = rand.nextInt(11) - 5;
    }

    public int getX() { return x; }
    public int getY() { return y; }
    public int getSize() { return size; }
    public void setSize(int s) { size = s; }
    public void setX(int xIn) { x = xIn; }
    public void setY(int yIn) { y = yIn; }

    public void setImage(String imagePath) {
        try {
            image = ImageIO.read(new File(imagePath));
        } catch (IOException ioe) {
            System.out.println("Unable to load image file.");
        }
    }
    public Image getImage() { return image; }

    public boolean overlaps(Sprite s) {
        int locX = this.getX();
        int locY = this.getY();
        int overX = s.getX();
        int overY = s.getY();


        Rectangle R1 = new Rectangle(locX, locY, this.w, this.h);
        Rectangle R2 = new Rectangle(overX, overY, s.w, s.h );
        boolean intersects = R1.intersects(R2);
        return intersects;
    }

    public void update(Graphics g) {
        g.drawImage(getImage(), x, y, getSize(), getSize(), null);
    }

    public void move() {
        // Move the Sprite
        int x = getX() + xSlope;
        int y = getY() + ySlope;
        if (x < 0) x = w;
        if (x > w) x = 0;
        if (y < 0) y = h;
        if (y > h) y = 0;
        setX(x);
        setY(y);
    }

}

0 个答案:

没有答案