检测到libgdx传感器碰撞但条件代码没有触发

时间:2016-08-17 15:30:44

标签: java android libgdx box2d

我有一个奇怪的逻辑错误,我正试图解决,但是我撞墙,似乎找不到我的方式。也许这里的集体思想可以提供帮助!

那么,到底发生了什么:我在Box2D中创建了一个光盘,以及在box2D中创建的传感器盒。如果光盘与传感器发生碰撞,则逻辑很简单。你赢了!问题是,我可以检测到球和传感器之间的碰撞,但是条件,你赢得的代码不会被解雇。这是我正在使用的代码。

//instantiating the disc, ground, start platform, and win sensor
    disc = createCircleBody("Circle", 20, camera.viewportWidth / 2, 450, 0);
    disc.setUserData("disc");

    floor = createGround(tmpFloor);
    floor.setUserData("floor");

    platform = createPlatform(initPlatform);
    platform.setUserData("platform");

    winSensor = createWinSensor(tmpWinSensor);
    winSensor.setUserData("winSensor");

    //...   Code omitted for clarity   ... 

    world.setContactListener(new ContactListener() {

        @Override
        public void beginContact(Contact contact) {

            Body fixtureA = contact.getFixtureA().getBody();
            Body fixtureB = contact.getFixtureB().getBody();

            // if the disc and the floor collide.
            if((fixtureA.getUserData() == disc.getUserData() && fixtureB.getUserData() == floor.getUserData()) || (fixtureA.getUserData() == floor.getUserData() && fixtureB.getUserData() == disc.getUserData())) {
                newDisc.add(tmpDisc);
                newDisc.add(tmpPlatform);
                bodiesForDeletion.add(disc);    // destroy the current disk
            }

            // if contact is detected between disc and WinSensor
            if (fixtureA.getUserData() == winSensor.getUserData() && fixtureB == disc.getUserData()) {

                Gdx.app.log("WIN_CONDITION", "You won!"); // This line won't fire. 

                //TODO: Create alert Box to notify user that they have won the game!
            }

            Gdx.app.log("beginContact", "between " + contact.getFixtureA().getBody().getUserData() + " and " + contact.getFixtureB().getBody().getUserData() + ".");
        }

        @Override
        public void endContact(Contact contact) {

            Body fixtureA = contact.getFixtureA().getBody();
            Body fixtureB = contact.getFixtureB().getBody();

            Gdx.app.log("endContact", "between " + contact.getFixtureA().getBody().getUserData() + " and " + contact.getFixtureB().getBody().getUserData() + ".");
        }

        @Override
        public void postSolve(Contact arg0, ContactImpulse arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void preSolve(Contact arg0, Manifold arg1) {
            // TODO Auto-generated method stub
        }
    });

第一次碰撞检测按预期工作。光盘与地面盒碰撞,被删除,并在世界步骤之外创建起始平台和新光盘。我无法弄清楚为什么这段代码没有被解雇。

1 个答案:

答案 0 :(得分:0)

好像在你的if语句中

  

if (fixtureA.getUserData() == winSensor.getUserData() && fixtureB == disc.getUserData()) {

.getUserData()上遗漏了fixtureB