Search code examples
javaswingcollision-detection

How to fix getBound method in java?


enter image description here

this is simple java game and it contains craft.java and wall.java class.All red line in picture is object of wall class

public void buildWall(){

        walls.add(new Wall(10,10,getWidth()-10, 10));
        walls.add(new Wall(10,10,10,getHeight()-10));
        walls.add(new Wall(10,getHeight()-10,getWidth()-10,getHeight()-10));
        walls.add(new Wall(getWidth()-10, getHeight()-10, getWidth()-10, 10));
        walls.add(new Wall(100, 10, 100, 50));
        walls.add(new Wall(150, 10, 150, 50));

    }

and i write a getBound2D() method for define the lines

public Wall(int x, int y , int z , int v){

         this.x = x;
         this.y = y;
         this.z = z;
         this.v = v;
         vis = true;

         line = new Line2D.Double(x,y,z,v);
     }

    @Override
    public Rectangle2D getBounds2D() {
        return new Rectangle(x,y,z,v);
    }

but this method is not working correctly. My purpose is when aircraft is touch the any one of line check collision and will game over . How should i fix it ?


Solution

  • Line has its own getBounds so you can use that:

    it has getBounds() and getBounds2D();

    the width of a vertical line is zero and the height of a horizontal line is zero.

    System.out.println(new Line2D.Double(0, 0, 0, 100).getBounds()+" "+new Line2D.Double(0, 0, 100, 0).getBounds2D());
    

    To have your vertical/horizontal lines have width/height 1 you can define it so:

    getBounds2D() {
      return new Rectangle(x, y, z-x+1, v-y+1);
    }