-2

Consider having an ArrayList<Rectangle> rectangles = new ArrayList(); and a Player Class that has a rectangle variable, Character c = new Character(new Rectangle(x,y,w,h));. The Character class has an update() like so :

public void update(){
rectangle.x = rectangle.x + xSpeed;
rectangle.y = rectangle.y + ySpeed;
}

Where xSpeed & ySpeed are constantly changing and update() is constantly called.

How do I correctly check if character rectangle and any rectangle in the ArrayList are intersecting and if so prevent the character rectangle from moving?

TheBoxOkay
  • 81
  • 1
  • 8
  • 1
    Seems you haven't even attempted it yourself, by the looks of your code. Please put some more effort into it. This is not a walkthrough site. Come back when you have a specific problem – Vince Dec 18 '15 at 21:34

1 Answers1

0

Look at the Rectangle API, you will see an intersects(Rectangle r) method that you can use. Intersects Method

You can check for collisions every update by using a loop to compare your object with all object rectangles in the ArrayList. If the method returns true, then you handle the collision however you like.

Sterls
  • 723
  • 12
  • 22
  • Yes im aware of this, but I understand that there is a specified way to handle hit detection in a game so that the update method is prevented from moving the rectangle – TheBoxOkay Dec 18 '15 at 22:48
  • You need to update before you draw. And before you accept the updated results, that's when you check the collisions. Create temporary updated x and y values, then check for the collisions, if there are none, then you set the real x and y to the temp positions. You need to make another loop to compare the current object with all other objects. Alternatively, you can manually check the edges of all rectangles to all others. But this is only for specific usage and I don't know how your objects are supposed to react. – Sterls Dec 18 '15 at 23:01