Rectangle Collision

I am making a collision detection method in my lwjgl game but it is not really working out. I am using Rectangles to check if they intersect. This is how I do it:

I have a Player that moves with the wasd buttons and I give him a Rectangle like this:

private Rectangle Collider;

public Player(int x, int y, int width, int height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		Collider = new Rectangle(x, y, width, height);
		}
		
		public Rectangle getCollider() {
		return Collider;
	}

I have an Item that looks like this:

private Rectangle Collider;

public Item(int x, int y, int width, int height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		Collider = new Rectangle(x, y, width, height);
		}
		
		public Rectangle getCollider() {
		return Collider;

                public void Update(){
                System.out.println("Updating Item");
                if(Canvas.iscolliding(game.player.getCollider(), this.getCollider)){
                    System.out.println("Colliding");
}
}
	}

And this is my iscolliding method:

public static boolean isColliding(Rectangle a, Rectangle b) {
		if (a.intersects(b)) {
			return true;
		} else {
			return false;
		}
	}

But it never prints colliding why? (I use the LWJGL Rectangle not the java.awt).

I assume this isn’t the actual code your running, since you’re calling “iscolliding()” rather than “isColliding()”.

Apart from that I can’t see anything wrong with your code. Have you tried hard-coding a test? e.g. doing a simple “return new Rectangle(0, 0, 10, 10).intersects(new Rectangle(5, 5, 10, 10);”, to check the function works. Maybe also output the rectangle’s values to the console just before the collision so you can check them for sanity.

Problem solved it was just a very stupid mistake by me. I set the Rectangle of the player when I create the player but I didnt update it to the new player coords after moving the player. So the Rectangle did not follow the player. XD

Another question how do I make it so the one rectangle cant enter the other one?

Make it so if they intersect (lets say you’re moving to the right) then the moving rectangle’s coordinate’s would be “current coordinate - 1”. so like this: (but you will also have to do a check to see which direction the player is going)

a is the player

if(a.intersects.b){
if(player_is_moving_right)
a.setX(a.getX() - 1);
}

And you would have to do the same thing for up, down, left, and right.

I preferred a slightly different approach to this problem.

What I did / do is :

Take the speed the object is travelling at, use that to determine the coordinates where the object will be after the frame, draw a line from each relevant point, find the intersection (if any) between the lines and the object it will hit, drop the speed down so that it will stop at the edge and flag the collision.