0
votes

I'm very new to libgdx and game dev. Ive been tasked with an assignment where I am given a very simple 2D game which has rectangular collision detection already implemented.

The game is just made up of a square which can be controlled by the player, which is inside of walls with other scattered squares within the walls. I now need to implement pixel perfect collision between the player square and the scattered squares/walls.

I originally tried using Pixmap and tried to check if the pixels of the current coordinate were transparent for the player rectangle and whichever rectangle it is colliding with but am having trouble implementing the code correctly.

I understand that I must just check the pixel colors for both objects at a certain coordinate and see if they both are not transparent for a collision to occur but I am having trouble. I have spent a very long time researching and looking online so any help or advice on how to execute this would be greatly appreciated!

public boolean entityCollision(Entity e1, Direction direction, float newX, float newY) {
    boolean collision = false;

    for(int i = 0; i < entities.size(); i++) {
        Entity e2 = entities.get(i);

        if (e1 != e2) {

            if (newX < e2.x + e2.width && e2.x < newX + e1.width &&
                newY < e2.y + e2.height && e2.y < newY + e1.height) {
                collision = true;

                int colorOne = player.getPixel((int)newX,(int)newY);
                int colorTwo = enemy.getPixel((int)e2.x,(int)e2.y);

                if (colorOne != 0 && colorTwo != 0) {
                  collision = true;
                  e1.entityCollision(e2, newX, newY, direction);
                }
            }
        }
    }

    return collision;
}
2

2 Answers

1
votes

Take a look at the Rectangle implementation of libgdx. It allows you to do something like this:

Rectangle e1Rec = new Rectangle(e1.x, e1.y, e1.width, e1.height);
Rectangle e2Rec = new Rectangle(e2.x, e2.y, e2.width, e2.height);

if (e1Rec.contains(e2Rec)) {
   // Collision!
}
0
votes

If you want collisions with a sprite, you get the sprite rectangle and check for collisions inside of that rectangle.

sprite.getboundingrectangle().contains(x, y) ; //returns a boolean