1

I need to know when the rocket hit the meteor, img2 is the meteor and img is the rocket

g.drawImage(img, posX - img.getWidth(this)/2, posY - img.getHeight(this), this);
        g.drawImage(img2,posX1 - img2.getWidth(this), posY1 - img2.getHeight(this),this);
        System.out.println(posY-img.getWidth(this));
        System.out.println(posY1);
      }
      public void colid (){
        if (posY1+img.getWidth(this)>= posY-img2.getWidth(this) ){

            System.out.println("teste");
        }
Giovanni
  • 13
  • 6
  • Is it a test or a teste? – DarkJade Apr 01 '16 at 23:10
  • Please fix your code, as it stands, it will not compile (are there missing lines above the first curly bracket?) – blurfus Apr 01 '16 at 23:14
  • this is only a part of the code. Test – Giovanni Apr 01 '16 at 23:19
  • Do you just want to do simple rectangular collision, for [example](http://stackoverflow.com/questions/30251027/creating-many-objects-with-collision-properties-java/30251268#30251268), [exmaple](http://stackoverflow.com/questions/21153110/brick-collision-java/21153384#21153384), [example](http://stackoverflow.com/questions/20927189/detecting-collision-of-two-sprites-that-can-rotate/20928531#20928531), [example](http://stackoverflow.com/questions/13261767/java-ball-object-doesnt-bounce-off-of-drawn-rectangles-like-its-supposed-to/13263022#13263022) – MadProgrammer Apr 01 '16 at 23:19
  • Or do you want to know when the non-alpha pixels collide, for [example](http://stackoverflow.com/questions/23332096/how-to-detect-if-two-images-collide-in-java/23332186#23332186)? – MadProgrammer Apr 01 '16 at 23:20

2 Answers2

0

You can create a Rectangle for every object like for a rocket or meteor

and there is a Rectangle method you can use

boolean intersects(Rectangle r)
Determines whether or not this Rectangle and the specified Rectangle intersect.

so you could check

if (rectangleA.intersects(rectangleB){
 System.out.println("Colliosion!!")
}
0

This should do it

        Rectangle r1 = new Rectangle(posX - img.getWidth(this)/2, posY - img.getHeight(this), img.getWidth(this), img.getHeight(this));
        Rectangle r2 = new Rectangle(posX1 - img2.getWidth(this), posY1 - img2.getHeight(this), img2.getWidth(this), img2.getHeight(this));

        boolean collision = r1.intersects(r2);

Note: You are dividing the width with 2 in the first image and not the second. Maybe it is as it should be but just want to let you know if it is not.

gustf
  • 1,959
  • 13
  • 20