I’m trying to use AABB collision in a platformer, but It’s not working correctly no matter how I change it. Here is the core setup for it. The player can jump and collide with the floor (for some reason i call it enemy) but if it touches the sides, it comes back up. Any tips or solutions? I’ve been going at this for far too long.
public class AABBDemo {
public AABBDemo() {
try {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.setTitle("test");
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 640, 480, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
Rectangle A = new Rectangle(100, 100, 50, 50);//player
Rectangle B = new Rectangle(100, 300, 90, 20);//enemy
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
int xVel = 0;
int yVel = 1;
int size = 50;
boolean jumping = false;
float jump = 0;
boolean jumped = false;
while (!Display.isCloseRequested()) {
glClear(GL_COLOR_BUFFER_BIT);
A.setX(A.getX() + xVel);
A.setY(A.getY() + yVel);
if(jumping)
{
A.setY((int) (A.getY() - jump));
jump -= 0.3f;
if(jump < -5)
jump = -5;
}
if(!jumping)
jump = 10;
if(A.getX() < 0 || A.getX() + size > 640 || check_collision(A, B))
{
jumping = false;
A.setX(A.getX() - xVel);
A.setY(A.getY() - 2);
}
if(Keyboard.isKeyDown(Keyboard.KEY_D))
xVel = 2;
else if(Keyboard.isKeyDown(Keyboard.KEY_A))
xVel = -2;
else
xVel = 0;
if(Keyboard.isKeyDown(Keyboard.KEY_W) && !jumping && !jumped)
{
jumped = true;
jumping = true;
}
if(!Keyboard.isKeyDown(Keyboard.KEY_W))
jumped = false;
glBegin(GL_QUADS);
glColor3f(1, 0, 0);
glVertex2i(A.getX(), A.getY()); // Upper-left
glVertex2i(A.getX() + A.getWidth(), A.getY()); // Upper-right
glVertex2i(A.getX() + A.getWidth(), A.getY() +A.getHeight()); // Bottom-right
glVertex2i(A.getX(), A.getY() + A.getHeight()); // Bottom-left
glEnd();
glBegin(GL_QUADS);
glColor3f(0, 1, 0);
glVertex2i(B.getX(), B.getY());
glVertex2i(B.getX() + B.getWidth(), B.getY());
glVertex2i(B.getX() + B.getWidth(), B.getY() + B.getHeight());
glVertex2i(B.getX(), B.getY() + B.getHeight());
glEnd();
Display.update();
Display.sync(60);
}
Display.destroy();
System.exit(0);
}
public boolean check_collision( Rectangle A, Rectangle B )
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of rect A
leftA = A.getX();
rightA = A.getX() + A.getWidth();
topA = A.getY();
bottomA = A.getY() + A.getHeight();
//Calculate the sides of rect B
leftB = B.getX();
rightB = B.getX() + B.getWidth();
topB = B.getY();
bottomB = B.getY() + B.getHeight();
//If any of the sides from A are outside of B
if( bottomA <= topB )
{
return false;
}
if( topA >= bottomB )
{
return false;
}
if( rightA <= leftB )
{
return false;
}
if( leftA >= rightB )
{
return false;
}
//If none of the sides from A are outside B
return true;
}
public static void main(String[] args) {
new AABBDemo();
}
}