简体   繁体   中英

libgdx how to detect collisions?

I have a Problem to detect collisions. I'm using TiledMap and created a virtual joystick, so that its possible to move in every direction not just left, right, top, bottom. The Point of View is directly 90 degrees from the top.

I don't know if that's the purpose of a TiledMap, but I thought the maps are easy to create. But now I 've got Problems with the collision detection. Since the map is not arranged like a chessboard, for example, I need to check the whole Sprite for collision. Can you please explain me to how that works?

Thank You

First of all I recommend you to checkout this question to clear up some things, and to get a basic Idea how collision detection works with TiledMaps .

Summarized: Using a TileEditor you can add different layers to your TiledMap . One of theese layers can be a object layer which can be used for collision. For how to create and access the layer please checkout the linked question.

For your example there are some central questions which needs to be cleared out first:

  1. Which shape and size do the colliding objects have?
  2. Can the objects move in between two tiles?
  3. What should happen on collision?

Pokemon is a super easy example. The Player has the size of exactly one tile and can not move in between them. If there is a collision the player just can't move.

If that is what you want you can just add a check before moving any object: If the next tile isn't valid just don't move the object. For the collision check you can just adapt the example code from the first answer .

On the other end of the specturm you could have different shaped objects with differnt scales which have a dynamic velocity and should bounce of the objects on the TileMap. In that case it could be clever to use box2d for collision detection like in this answer .

So depending on your needs just try to adapt any of the answers I linked. Maybe just start with a super simple box collision try to extend your code.

use this method

 void isCollition(Object x, Object y) {
    Boolean collide = false;
    if (x.getX() + x.getwidth() < y.getX() + y.getWidth() ||
            x.getY() + x.getHeight() < y.getY() + y.getHeight() {
        collide = true;
    }
    return collide;
}

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