如何检测多边形内部的命中,而不是LibGDX + Box2d

时间:2016-04-30 09:26:44

标签: libgdx box2d

我有一个由下一个代码定义的实体Actor:

        this.world = world;
        this.texture = texture;

        // Create the body.
        BodyDef def = new BodyDef();                // (1) Give it some definition.
        def.position.set(x, y + 0.5f);              // (2) Position the body on the world
        def.type = BodyDef.BodyType.DynamicBody;
        body = world.createBody(def);               // (3) Create the body.

        // Now give it a shape.

        PolygonShape box = new PolygonShape();      // (1) We will make a polygon.
        Vector2[] vertices = new Vector2[6];
        vertices[0] = new Vector2(0.04f  , 0.24f  );
        vertices[1] = new Vector2(0.64f , 1.18f  );
        vertices[2] = new Vector2(1.66f , 1.8f);
        vertices[3] = new Vector2(1.92f , 1.52f);
        vertices[4] = new Vector2(1.18f , 0.66f);
        vertices[5] = new Vector2(0.26f , 0.03f);

        box.set(vertices);                          // (4) And put them in the shape.
        fixture = body.createFixture(box, 3);       // (5) Create the fixture.
        fixture.setUserData("actor");               // (6) And set the user data to enemy.
        box.dispose();                              // (7) Destroy the shape when you don't need it.

        // Position the actor in the screen by converting the meters to pixels.
        setPosition((x - 0.5f) * PIXELS_IN_METER, y * PIXELS_IN_METER);
        setSize(PIXELS_IN_METER, PIXELS_IN_METER);
        this.setDebug(true);

当我添加最后一行setDebug时,我的Actor abject被一个方形的形状包围,我的命中影响到这个方块,而不是我的poligon定义的REAL形状。此命中检测由touchDown(InputProcessor)事件捕获:

    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector2 coord = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
    Actor hitActor = stage.hit(coord.x,coord.y,false);
    if(hitActor != null) {
        Gdx.app.log("myapp", "hit!!!!!");
    }
    return true;
}

我做错了什么?我只是想检测我的游戏演员项目的命中。 提前谢谢!!

1 个答案:

答案 0 :(得分:0)

Scene2D actor和Box2D正文不一样 - 如果你想看到 body 正在调试你必须使用Box2D的DebugRenderer

    //creating debug renderer in show method or as class'es field
    Box2DDebugRenderer debugRenderer = new Box2DDebugRenderer();

    //render() method
    debugRenderer.render(world, camera.combined);

然后你会看到你的身体形状和演员的形状不一样。更糟糕的是他们可能不会有相同的位置,因为你没有因为身体更新你的演员的位置(你应该在演员的行为覆盖方法中使用setPosition(body.getPosition().x, body.getPosition().y); - 请记住,当身体的原点位于中心时,演员的原点位于左下角!)。

不幸的是,演员只能是长方形,因此无法创建与身体相同的形状。但是你可以使用actor作为边界框,并将它的大小设置为与整个身体重叠(如果身体旋转,它将会改变!)。

另一种解决方案不是捕获正文上的侦听器,而是实现某些机制,例如在单击并检查碰撞后创建主体