0

This should be a very easy question, basically I have two squares, and I'm trying to see if they overlap. So far I've figured out the right and bottom collisions, but I can't figure out collisions from the left and top. Here's my code:

if (e.getX() >= player.getX() && e.getX() <= player.getX() + Entity.SIZE && e.getY() >= player.getY() && e.getY() <= player.getY() + Entity.SIZE) {
   return true;

Let e be the entity that I'm checking and Entity.SIZE be the size for both the squares. What am I doing wrong?

2 Answers2

0

I would suggest just making the player and every entity have a bounding rectangle using java's Rectangle class. You can do easy operations like:

if(e.boundingBox.intersects(player.boundingBox)){...}

where each entity has something like:

private Rectangle boundingBox;
Will
  • 373
  • 2
  • 7
  • 1
    I don't want to do this as I'm using straight LWJGL and I want to learn all the math behind making games. Besides, I already know about the Rectangle class. The fix was simple, I left out a tiny bit of code. –  Dec 02 '13 at 03:07
  • 1
    @opiop65: That's great and everything, but you would have saved time by specifying your requirements in the original answer. Bounding boxes are the traditional (and simpler) method of collision detection, so it's no wonder that Will suggested using that approach. I immediately thought of bounding boxes when I read your question myself. – MarsAtomic Dec 02 '13 at 03:11
  • Am I not using bounding boxes myself? Sure, I don't create a actual bounding box, but I'm doing the same thing as the .intersects function. If I post about a math question, I expect to get a answer related to what I asked. Assuming I want to dumb things down for myself is not the way to go, and actually using the Rectangle method would have been slower considering I would have to refactor most of my code just to get it to work, and then I would have to re-implement my collision response accordingly. Don't over think these things, just give me what I'm asking for. –  Dec 02 '13 at 03:20
0

Silly me, I forgot to check for the size on the x and y axis when above or next to a rectangle. Here's the new code:

e.getX() + Entity.SIZE >= player.getX() && e.getX() <= player.getX() + Entity.SIZE && e.getY() + Entity.SIZE >= player.getY() && e.getY() <= player.getY() + Entity.SIZE