Results 1 to 2 of 2
  1. #1
    CNew is offline Member
    Join Date
    Dec 2010
    Posts
    27
    Rep Power
    0

    Default Collision between 2 rectangles

    Here are my 2 rectangles:

    g.setColor(Color.GREEN);
    g.fillRect(rect.x,rect.y,rect.width,rect.height);

    g.setColor(Color.WHITE);
    g.fillRect(x, y,rect2.width,rect2.width);




    It has the x and y coordinates and the width and height for both, but i cant figure out how to have the collision detected. Im new to this so i dont really know what to do. The only thing ive tried is


    if x<=(rect.x +rect.width);{
    JOptionPane.showMessageDialog(frame, "You Lose");

    Any help would be appreciated!

  2. #2
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    Draw this on a piece of paper:
    1) A rectangle intersecting another rectangle.
    2) A rectangle beside another rectangle.

    From here, you can figure out the exact criteria that you need in order for your rectangles to overlap. (That is, what combination of Xs and widths constitute a horizontal overlap, and the same for Ys and heights for a vertical overlap).

    Next, you can put this to a series of statements in your program. Say, for example, that a requirement is that your X value plus Width is greater than the target's X value. You'd do something like this: (x + width > rect.x).

    Then you can put this to an if statement like yours above. If I were you though I'd take another look at that though--your if statement isn't quite proper syntax.

Similar Threads

  1. Why only one of the two rectangles is painted?
    By JOHNINALBANY in forum Java 2D
    Replies: 5
    Last Post: 07-07-2012, 10:54 PM
  2. Drawing Rectangles - NullPointerExceptions
    By cselic in forum Java 2D
    Replies: 4
    Last Post: 05-20-2010, 02:37 PM
  3. Replies: 3
    Last Post: 05-05-2010, 01:15 PM
  4. Rectangles method
    By bdario1 in forum New To Java
    Replies: 31
    Last Post: 03-31-2010, 09:32 PM
  5. How to Draw Round Rectangles in SWT
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 06-28-2008, 09:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •