如何获取图像对象的位置

suzh9iv8  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(325)

我正在开发一个垂直滚动游戏,为了创建命中检测/碰撞,我决定从rectangle类中删除intersects方法:

public boolean intersects(Rectangle r){
  return r.width > 0 && r.height > 0 && width > 0 && height > 0
   && r.x < x + width && r.x + r.width > x
   && r.y < y + height && r.y + r.height > y; }

并用图像方法改变这种方法的所有“内部成分”。问题是,image类中没有像“.getx()”那样返回jpanel上图像对象的位置的方法。我试图为屏幕上的每个图像创建一个单独的矩形对象,并将其用作一个hitbox,但这似乎有点浪费,我已经没有主意了。

cbeh67ev

cbeh67ev1#

这是我很久以前做的事:
基本上是为了你的 GameObject 您应该有一个类来封装 GameObject 它的数据(如x,y,高度和宽度等),这个类应该有一个 Rectangle2D 与它有关的任何运动 GameObject 事实上应该移动 Rectangle2D 与之相关的代码如下:

class GameObject extends Animator {

    protected Rectangle2D.Double rectangle;

    public GameObject(int x, int y, ArrayList<BufferedImage> frames, ArrayList<Long> timings, int pos, int conW, int conH) {
        super(frames, timings);
        //...
        // I have a list of images thats set in the Animator class but if you had one image you would have the setter for it here and it would be passed into the constructor and this GameObject would have a getCurrentImage or similar method which returns the BufferedImage associated with the GameObject.
        rectangle = new Rectangle2D.Double(x, y, getCurrentImage().getWidth(), getCurrentImage().getHeight());
        //...
    }

    public void setX(double x) {
        rectangle.x = x;
    }

    public void setY(double y) {
        rectangle.y = y;
    }

    public void setWidth(double width) {
        rectangle.width = width;
    }

    public void setHeight(double height) {
        rectangle.height = height;
    }

    public double getX() {
        return rectangle.x;
    }

    public double getY() {
        return rectangle.y;
    }

    public double getWidth() {
        if (getCurrentImage() == null) {//there might be no image (which is unwanted ofcourse but  we must not get NPE so we check for null and return 0
            return rectangle.width = 0;
        }

        return rectangle.width = getCurrentImage().getWidth();
    }

    public double getHeight() {
        if (getCurrentImage() == null) {
            return rectangle.height = 0;
        }
        return rectangle.height = getCurrentImage().getHeight();
    }

    public Rectangle2D getBounds2D() {
        return rectangle.getBounds2D();
    }

    public boolean intersects(GameObject go) {
        return rectangle.intersects(go.getBounds2D());
    }
}

然后你只要画你的 GameObject 使用下面的逻辑(您得到 GameObject 以及相关矩形的x和y坐标):

g2d.drawImage(gameObject.getCurrentImage(), (int) gameObject.getX(), (int) gameObject.getY(), null);

然后你可以使用 Rectangle2D 学生:

rectangle.getBounds2D();

它将返回一个 Rectangle2D 这样你就可以简单地调用 Rectangle2D#intersects 方法(参见 getBounds2D 以及 intersects(GameObject go) 以上的 GameObject 类别),即:

gameObject.intersects(anotherGameObject)

相关问题