Java-libGdx-三角形和矩形之间的碰撞无法正常工作

时间:2018-11-25 22:02:32

标签: java libgdx collision

我正在libgdx中制作简单的android游戏。我想防止三角形(主字符)和矩形(墙)之间重叠。我正在使用此功能来防止重叠:

public boolean overlaps(MyActor other)
{
    Polygon poly1 = this.getBoundaryPolygon();
    Polygon poly2 = other.getBoundaryPolygon();

    if(!poly1.getBoundingRectangle().overlaps(poly2.getBoundingRectangle()))
        return false;

    return Intersector.overlapConvexPolygons(poly1,poly2);
}

public Vector2 preventOverlap(MyActor other)
{
    Polygon poly1 = this.getBoundaryPolygon();
    Polygon poly2 = other.getBoundaryPolygon();

    if(!poly1.getBoundingRectangle().overlaps(poly2.getBoundingRectangle()))
       return null;

    Intersector.MinimumTranslationVector mtv = new Intersector.MinimumTranslationVector();
    boolean polygonOverlap = Intersector.overlapConvexPolygons(poly1,poly2,mtv);

    if(!polygonOverlap)
        return null;

    this.moveBy(mtv.depth * mtv.normal.x,mtv.depth * mtv.normal.y);
    return mtv.normal;
}

这是我为三角形创建边界多边形的方法:

public void setBoundaryTriangle()
{
    float[] vertices = new float[6];

    vertices[0] = 0;
    vertices[1] = 0;
    vertices[2] = getWidth();
    vertices[3] = 0;
    vertices[4] = getWidth() / 2;
    vertices[5] = getHeight();

    boundaryPolygon = new Polygon(vertices);
}

,对于矩形:

public void setBoundaryRectangle()
{
    float w = getWidth();
    float h = getHeight();
    float[] vertices = {0,0,w,0,w,h,0,h};
    boundaryPolygon = new Polygon(vertices);
}

这是getBoundryPolygon方法:

public Polygon getBoundaryPolygon()
{
    boundaryPolygon.setPosition(getX(),getY());
    boundaryPolygon.setOrigin(getOriginX(),getOriginY());
    boundaryPolygon.setRotation(getRotation());
    boundaryPolygon.setScale(getScaleX(),getScaleY());

    return boundaryPolygon;
}

所以,我有两个矩形-一个在屏幕的左侧,另一个在右侧。三角形从屏幕中心开始,然后将其向左或向右移动。我还旋转三角形以检查碰撞检测是否在其所有侧面和边缘上都有效。当我将三角形向右移动并与右矩形接触时,preventOverlap方法可以正常工作。但是,当我将三角形向左移动并与左矩形接触时,preventOverlap方法仅在三角形以其边缘之一接触壁时,在三角形以其侧面之一接触壁时才有效(当我旋转三角形和两侧是平行的)它可以快速穿过墙壁。

之所以发生这种情况,是因为mtv.normal.x == -1.0(分离的方向)并且三角形移到了墙的另一侧。但是我不明白为什么Intersector.overlapConvexPolygons(poly1,poly2,mtv)将mtv.normal.x设置为-1.0,这是错误的。

这是Intersector类:https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/math/Intersector.html

0 个答案:

没有答案
相关问题