简体   繁体   中英

Libgdx: Tiled Objects layer for collision

Good day sirs,

I'm trying to figure out now is how to perform a collision detection for my player by using a Tiled Object layer, to be more specific I wanted it to detect a polyline which I have draw in my tiled map. As I was researching in google about collision detection for Tiled, I found this simple example superkoala sample for TiledmapLayer . In my understanding of the code (correct me if I'm wrong), It order to detect a collision the player will read each tile of a certain layer for example a foreground layer which contains the ground and other objects.

Basically, What I did with my Object layer is I named my polyline to Wall and for the type I put in numbers depending on how many polylines I have used. So that for future use I could call this wall numbers for my collision.

Can anyone give me a sample code about reading objects and using them for collision detection?or just a simple tip or Idea on how I could solve this?any help would be appreciated.

What i recommend on doing in your case is not to use object layers but properties for the specific tiles. Let's say you have one tile in 'Tiled' and you are sure to only use it as a wall. Click on that specific tile and add the property "blocked". Then, in your code, you can check every cell next to the player and if it contains the property "blocked", not allow the player to go in that direction. Here is a pseudo-code on how I did it:

private boolean isCellBlocked(float x, float y) {
    Cell cell = null;
    boolean blocked = false;

    try {
        cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (cell != null && cell.getTile() != null) {
        if (cell.getTile().getProperties().containsKey("blocked")) {
            blocked = true;
        }
    }
    return blocked;
}

and you can make the player call isCellBlocked(x, y) every time he updates.

I also did a collidesSide(float x, float y) for every side ( collidesTop(float x, float y) , etc).

I hope this helps you out, even if it doesn't use the system you wanted to. For any more help on this, I'm heavily using libGDX for my collision detection on a big project, so don't hesitate to contact me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM