Search code examples
javaeclipsegame-enginecollisionjava-2d

Custom collisionbox


I'm using eclipse to create my own game engine. I do all the rendering with square tiles, but I now have some sprites that don't need the edge of the sprite to be the place to collide. Is it possible to make a custom collisionbox on pixel level?

In the code below you can see I use the player speed over the x and y direction to test if there's a "solid" block which he collides with, but I want it to have a custom collisionbox instead of the edge.

public boolean hasCollided(int xa, int ya) {
    int xMin = 0;
    int xMax = 8;
    int yMin = 0;
    int yMax = 5;

    for (int x = xMin; x < xMax; x++) {
        if (isSolidTile(xa, ya, x, yMin) || isSolidObject(xa, ya, x, yMin)) {
            return true;
        }
    }
    for (int x = xMin; x < xMax; x++) {
        if (isSolidTile(xa, ya, x, yMax) || isSolidObject(xa, ya, x, yMax)) {
            return true;
        }
    }
    for (int y = yMin; y < yMax; y++) {
        if (isSolidTile(xa, ya, xMin, y) || isSolidObject(xa, ya, xMin, y)) {
            return true;
        }
    }
    for (int y = yMin; y < yMax; y++) {
        if (isSolidTile(xa, ya, xMax, y) || isSolidObject(xa, ya, xMax, y)) {
            return true;
        }
    }
    return false;
}

And here is the isSolidObject, because the tile part is working

protected boolean isSolidObject(int xa, int ya, int x, int y) {
    if(level == null) {
        return false;
    }

    GameObject newObject = level.getGameObject((this.x + x + xa) >> 4, (this.y + y + ya) >> 4);

    if(newObject.isSolid()) {
        return true;
    }
    return false;
}

Thanks in advance!


Solution

  • maybe you find this in https://www.lwjgl.org/ Lightweight Java Game Library (open source) or http://slick.ninjacave.com/ (open source game library)

    in this thread is a collision detection with Slick2D Slick2D Rectangle Collision Detection

    (for C++ there is a complete open source game-engine http://www.cocos2d-x.org/)

    For HTML5 games there is phaser.io http://phaser.io/ (this is really nice...)