简体   繁体   中英

Collision detection in libgdx for triangles

I am making a simple game with libgdx and wanted to add some simple collision detection. I already managed to express my player by using a simple rectangle:

boundingBox = new Rectangle(x + 10, y + 10, 13, 21);

but my obstacles seem to be much more complicated. They are supposed to be spikes over which the player can jump and have a triangle shape. They pretty much look like this: http://kayin.pyoko.org/iwbtg/forums/Smileys/iwbtg/spikes.gif

As far as I noticed there is no triangle shape in libgdx. I already tried using polygons but they seem far too complicated for my purposes.

Is there an easy way to implement an accurate hitbox for them?

Thanks in advance for reading my post : )

EDIT: Thanks everyone for your responses, everything works fine now, besides drawing my polygons for testing purposes. When I call

shapeRenderer.polygon(kid.getVertices());

it only draws my polygon in the top left corner, since it's defined as

boundingBox2.setVertices(new float[] { 10, 10, 10, 31, 23, 31, 23, 10 });

But I move it around in the update method of my kid class by using

boundingBox2.setPosition(position.x, position.y);

Is there a way to use that position change inside

shapeRenderer.polygon(kid.getVertices()); ?

Anyways I really appreciate your help and after sorting out this problem I will close this thread : )

Create a Polygon of your rectangle and your triangle. You can even create a custom polygon if you want to add more advanced shapes.

To convert from rectangle to polygon is very easy, i made a method some months ago

public static float[] rectangleToVertices(float x, float y, float width,
        float height) {
    float[] result = new float[8];
    result[0] = x;
    result[1] = y;

    result[2] = x + width;
    result[3] = y;

    result[4] = x + width;
    result[5] = y + height;
    result[6] = x;
    result[7] = y + height;

    return result;
}

The good thing about libGDX polygon class is that you can move your polygon or even rotate it, and get the transformed vertices!

Now you can use the Intersector class

public static boolean overlapConvexPolygons(Polygon p1,
                            Polygon p2)
Check whether specified convex polygons overlap.
Parameters:
p1 - The first polygon.
p2 - The second polygon.
Returns:
Whether polygons overlap.

For testing purposes, after you end your sprite batch do like this

batch.end(); // you end your spritebatch
renderer.setProjectionMatrix(camera.combined);
renderer.begin(ShapeType.Line)
renderer.polygon(polygonname.getVertices());
renderer.end();

Now you will be able to see your polygon.

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