Collision Detection with some Rectangles

Hey everyone,
I started learning Java some weeks ago and tried to make a little game. It should be like this game.
I made some walls using rectangles and also a little ball. The collision works really great, but only with one rectangle, wich I wrote in the code like this:


public void checkCollision(){
		
		player = new Rectangle(player.x,player.y,player.width,player.height);
		
		rect = floor_mid;
		if (player.intersects(rect)){
			stopMovement();
			setOffWall(rect);
		}
	}

And the rectangles i’m using:

	
        public Rectangle floor_south;
	public Rectangle floor_north;
	public Rectangle floor_east;
	public Rectangle floor_west;
	public Rectangle floor_mid;
	
	public Rectangle player;

How can I code it so the player would stop on every rectangle?

You could put all the Rectangles into an array of rectangles then you can go through them all in a for loop e.g.


for(int i = 0; i < rectangles.length(); i++){
       if(player.intersects(rectangles[i])){
         stopMovement();
         setOffWall(rect);
       }
}

How do I do an array of recangles?

Like this: Rectangle[] rectangles = new Rectangles[1];
I would recommend creating an ArrayList instead. Like this: ArrayList rectangles = new ArrayList(), that way you don’t have to know the number of Rectangles at the beginning. You just keep adding Rectangles you need for collision detection to the list. Then you can iterator through the list.


Iterator<Rectengle> iter = rectangles.iterator();
while (iter.hasNext()) {
Rectangle rectangle = iter.next();
// Do your stuff here
}

Regards, :slight_smile:

Unless you actually need the iterator object (such as to remove things), you ought to use foreach syntax:


for (Rectangle r: rectangles) {
   // do stuff here
}