如何获取图像对象的位置

how to get the position of an Image object

我正在开发一款垂直滚动游戏,为了创建命中检测/碰撞,我决定从矩形中提取相交方法 class:

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; }

并用图像方法更改此方法的所有“内部组件”。 问题是,图像 Class 中没有方法 returns 图像对象在 jpanel 上的位置,如“.getX()”。我尝试为屏幕上的每个图像创建一个单独的 Rectangle 对象并将其用作碰撞框,但这似乎有点浪费,我 运行 出主意了。

This was something I did a long time ago:

基本上,对于您的 GameObject,您应该有一个 class,它封装了 GameObject 的图像及其数据(即 X , Y, heightwidth 等), 这个 class 应该有一个 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(你得到 GameObjectX 的图像Y 其关联的 矩形 的坐标):

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

然后您可以使用 Rectangle2Ds:

rectangle.getBounds2D();

这将 return 一个 Rectangle2D 并且你可以简单地调用内置的 Rectangle2D#intersects 方法(参见上面的 getBounds2Dintersects(GameObject go) GameObject class) 即:

gameObject.intersects(anotherGameObject)