Example usage for com.badlogic.gdx.physics.box2d ContactListener ContactListener

List of usage examples for com.badlogic.gdx.physics.box2d ContactListener ContactListener

Introduction

In this page you can find the example usage for com.badlogic.gdx.physics.box2d ContactListener ContactListener.

Prototype

ContactListener

Source Link

Usage

From source file:com.dongbat.game.system.Box2dSystem.java

private void setContactListener() {
    physicWorld.setContactListener(new ContactListener() {

        @Override//  ww w  .  j  a  v a2  s .  c  om
        public void beginContact(Contact contact) {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();
            UUID userDataA = (UUID) fixtureA.getBody().getUserData();
            UUID userDataB = (UUID) fixtureB.getBody().getUserData();

            addCollidedEntity(userDataA, userDataB);

        }

        @Override
        public void endContact(Contact contact) {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

            UUID userDataA = (UUID) fixtureA.getBody().getUserData();
            UUID userDataB = (UUID) fixtureB.getBody().getUserData();

            removeCollidedEntity(userDataA, userDataB);
        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
        }

    });
}

From source file:com.hatstick.fireman.physics.Box2DPhysicsWorld.java

License:Apache License

public void createPhysicsWorld() {

    xEngine = new ExplosionEngine();

    // create the debug renderer
    renderer = new Box2DDebugRenderer();

    // create the world
    world = new World(new Vector2(0, -3), true);

    bob.setBody(createPhysicsObject(bob.getBounds(), ModelType.PLAYER, -1).getBody());

    // Create our enemy's physical representations
    for (Map.Entry<Civilian, Integer> civilian : level.getEnemies().entrySet()) {
        civilian.getKey().setFixture(/*  w  w  w  . ja va2s. com*/
                createPhysicsObject(civilian.getKey().getBounds(), ModelType.ENEMY, civilian.getValue()));
    }

    // Create our item's physical representations
    for (Map.Entry<Item, Integer> item : level.getItems().entrySet()) {
        item.getKey()
                .setFixture(createPhysicsObject(item.getKey().getBounds(), ModelType.ITEM, item.getValue()));
    }

    // Create our level out of blocks
    for (Block block : level.getBlocks()) {
        createBoxes(block.getBounds());
    }

    //   createDestruction();

    world.setContactListener(new ContactListener() {
        @Override
        public void beginContact(Contact contact) {

            // Get our UserData object, and check for contacts
            UserData dataA = (UserData) contact.getFixtureA().getUserData();
            UserData dataB = (UserData) contact.getFixtureA().getUserData();

            /** Used for determining if character can jump or not **/
            if (dataA.modelType == ModelType.FOOT_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(1);
                    bob.canJump(true);
                }
            }
            if (dataB.modelType == ModelType.FOOT_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(1);
                }
            }

            if (dataA.modelType == ModelType.LEFT_SIDE_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumLeftSideContacts(1);
                    bob.canJump(true);
                }
            }
            if (dataB.modelType == ModelType.LEFT_SIDE_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumLeftSideContacts(1);
                }
            }

            if (dataA.modelType == ModelType.RIGHT_SIDE_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumRightSideContacts(1);
                    bob.canJump(true);
                }
            }
            if (dataB.modelType == ModelType.RIGHT_SIDE_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumRightSideContacts(1);
                }
            }

            /** Touching an item (used for picking up items) **/
            if (dataA.modelType == ModelType.PLAYER && dataB.modelType == ModelType.ITEM
                    || dataB.modelType == ModelType.ITEM && dataA.modelType == ModelType.PLAYER) {

                MouseJointDef def = new MouseJointDef();
                def.bodyA = contact.getFixtureA().getBody();
                def.bodyB = contact.getFixtureB().getBody();
                dataA = (UserData) def.bodyA.getUserData();
                def.collideConnected = false;
                def.target.set(testPoint.x, testPoint.y);

                if (dataA.modelType == ModelType.PLAYER) {
                    def.target.set(def.bodyA.getWorldCenter());
                    def.maxForce = 1000.0f * def.bodyA.getMass();
                } else {
                    def.target.set(def.bodyB.getWorldCenter());
                    def.maxForce = 1000.0f * def.bodyB.getMass();
                }
                jointsToCreate.add(def);
            }
        }

        @Override
        public void endContact(Contact contact) {
            // Get our UserData object, and check for contacts
            UserData dataA = (UserData) contact.getFixtureA().getUserData();
            UserData dataB = (UserData) contact.getFixtureA().getUserData();

            /** Used for determining if character can jump or not **/
            if (dataA.modelType == ModelType.FOOT_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(-1);
                }
            }
            if (dataB.modelType == ModelType.FOOT_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(-1);
                }
            }
        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
        }
    });
}

From source file:com.invader.collide.Loader.java

License:Open Source License

private ContactListener contactListener() {
    //On collision check what collided and do the respective
    ContactListener contactListener = new ContactListener() {
        Boolean Collided(Contact contact, Object str_a, Object str_b) {
            String A = (String) contact.getFixtureA().getBody().getUserData();
            String B = (String) contact.getFixtureB().getBody().getUserData();
            if ((A.contains(str_a.toString()) && B.contains(str_b.toString()))
                    || (A.contains(str_b.toString()) && B.contains(str_a.toString())))
                return true;
            else/*from   www  . jav  a 2 s.c  o  m*/
                return false;
        }

        public void beginContact(Contact contact) {

            if (Constants.Enable_Listener == 0)
                return;

            if (Collided(contact, "HOLE", "USER") || Collided(contact, "USER", "COMP")) {
                Constants.Enable_Listener = 0;
                Vibrator v = (Vibrator) Constants.context.getSystemService(Context.VIBRATOR_SERVICE);
                long vib[] = { 50, 100, 50, 100, 50, 100 };
                v.vibrate(vib, -1);
                Constants.toLoad = "LEVEL";
                Constants.sceneManager.needed_scene = Constants.SCENE.LOAD;
            } else if (Collided(contact, "COMP", "HOLE")) {
                int toremove;
                if (contact.getFixtureA().getBody().getUserData().toString().contains("COMP"))
                    toremove = Integer.valueOf(
                            contact.getFixtureA().getBody().getUserData().toString().replaceAll("[^0-9]", ""));
                else
                    toremove = Integer.valueOf(
                            contact.getFixtureB().getBody().getUserData().toString().replaceAll("[^0-9]", ""));
                Constants.sprite_Queue.add(toremove);
            } else if (Collided(contact, "USER", "GOAL")) {
                int toremove;
                if (contact.getFixtureA().getBody().getUserData().toString().contains("USER"))
                    toremove = Integer.valueOf(
                            contact.getFixtureA().getBody().getUserData().toString().replaceAll("[^0-9]", ""));
                else
                    toremove = Integer.valueOf(
                            contact.getFixtureB().getBody().getUserData().toString().replaceAll("[^0-9]", ""));
                Constants.sprite_Queue.add(toremove);
            }

        }

        public void endContact(Contact contact) {

        }

        public void preSolve(Contact contact, Manifold oldManifold) {

        }

        public void postSolve(Contact contact, ContactImpulse impulse) {

        }
    };
    return contactListener;
}

From source file:com.johnogel.astrobros.levels.Level.java

protected void initializeContactListener() {
    world.setContactListener(new ContactListener() {

        @Override/*from   w  w  w.  ja  va 2  s. c o  m*/
        public void beginContact(Contact contact) {
            boolean is_bro;

            //check if a bro is touching the sun
            if (contact.getFixtureA().getBody().equals(suns.get(0).getBody())
                    || contact.getFixtureB().getBody().equals(suns.get(0).getBody())) {

                sizzle = true;

                if (bro_bodies.contains(contact.getFixtureA().getBody(), true)) {
                    if (contact.getFixtureA().getBody().equals(player.getBody())) {
                        //notifyLoss();
                        dead = true;
                    }

                    //contact.getFixtureA().getBody().setActive(false);
                    for (AstroBro b : bros) {
                        if (b.getBody().equals(contact.getFixtureA().getBody())) {
                            b.setAlive(false);

                            to_be_destroyed.add(b.getBody());

                        }
                    }
                    /*free_bodies.removeValue(contact.getFixtureA().getBody(), true);
                    controlled_bodies.removeValue(contact.getFixtureA().getBody(), true);
                    bro_bodies.removeValue(contact.getFixtureA().getBody(), true);
                    mngr.removeGameObject(contact.getFixtureA().getBody());*/
                    //System.out.println("SO FAR SO GOOD!---------------");
                }

                if (bro_bodies.contains(contact.getFixtureB().getBody(), true)) {
                    if (contact.getFixtureB().getBody().equals(player.getBody())) {
                        //notifyLoss();
                        dead = true;
                    }

                    //contact.getFixtureB().getBody().setActive(false);
                    for (AstroBro b : bros) {
                        if (b.getBody().equals(contact.getFixtureB().getBody())) {
                            b.setAlive(false);

                        }
                    }
                    /*free_bodies.removeValue(contact.getFixtureB().getBody(), true);
                    controlled_bodies.removeValue(contact.getFixtureB().getBody(), true);
                    bro_bodies.removeValue(contact.getFixtureB().getBody(), true);
                    mngr.removeGameObject(contact.getFixtureB().getBody());*/

                    //System.out.println("SO FAR SO GOOD!---------------");
                }

            }
            //check if both contacts are bros
            if (bro_bodies.contains(contact.getFixtureA().getBody(), false)
                    && bro_bodies.contains(contact.getFixtureB().getBody(), false)) {

                if (sound_player != null) {
                    /*bump_sound_id = bump_sound.play(.5f);
                    bump_sound.setPitch(bump_sound_id, .55f);*/
                    //sound_player.playSound(SoundPlayer.BUMP_SOUND, .8f, .55f);
                    bumps++;
                }
                //System.out.println("THEY'RE BROS!!!!!!!!!!!!!!!!!!!!!");
                //if contact A is free and B is trying to grab
                if (free_bodies.contains(contact.getFixtureA().getBody(), false)
                        && controlled_bodies.contains(contact.getFixtureB().getBody(), false)) {
                    to_be_attached_to.add(contact.getFixtureB().getBody());
                    //finds which free bro exactly is being contacted
                    for (int i = 0; i < free_bros.size; i++) {

                        if (free_bros.get(i).getBody().equals(contact.getFixtureA().getBody())) {
                            //bro.getBody().setActive(false);
                            //bro.getBody().setType(BodyDef.BodyType.StaticBody);

                            to_be_attached.add(free_bros.get(i).getBody());

                            //System.out.println("RADIUS: "+free_bros.get(i).getRadius()*2);

                            joint_def_created = true;

                            //world.createJoint(joint_def);

                            //joint_def.initialize(joint_def.bodyA, joint_def.bodyB, new Vector2(contact.getFixtureB().getBody().getPosition().x+3, contact.getFixtureB().getBody().getPosition().y+3));
                            //free_bros.get(i).setTexture("badlogic.jpg");
                            /*controlled_bodies.add(free_bodies.removeIndex(free_bodies.indexOf(free_bros.get(i).getBody(), false)));
                            controlled_bros.add(free_bros.removeIndex(i));*/

                            //System.out.println("CONATACT!!!! BRO SHOULD HAVE BEEN ADDED TO OTHER ARRAY 1111");

                        }

                    }

                }

                //if contact B is free and A is trying to grab
                else if (free_bodies.contains(contact.getFixtureB().getBody(), false)
                        && controlled_bodies.contains(contact.getFixtureA().getBody(), false)) {

                    to_be_attached_to.add(contact.getFixtureA().getBody());

                    for (int i = 0; i < free_bros.size; i++) {

                        if (free_bros.get(i).getBody().equals(contact.getFixtureB().getBody())) {
                            //bro.getBody().setActive(false);
                            //bro.getBody().setType(BodyDef.BodyType.StaticBody);
                            //free_bros.get(i).setTexture("badlogic.jpg");
                            to_be_attached.add(free_bros.get(i).getBody());

                            joint_def_created = true;

                            //world.createJoint(joint_def);

                            //joint_def.initialize(joint_def.bodyA, joint_def.bodyB, new Vector2(contact.getFixtureA().getBody().getPosition().x+3, contact.getFixtureA().getBody().getPosition().y+3));

                            /*controlled_bodies.add(free_bodies.removeIndex(free_bodies.indexOf(free_bros.get(i).getBody(), false)));
                            controlled_bros.add(free_bros.removeIndex(i));*/
                            //System.out.println("CONATACT!!!! BRO SHOULD HAVE BEEN ADDED TO OTHER ARRAY 2222");

                        }

                    }
                }

                if (contact.getFixtureA().getBody().equals(outer_orbit.getBody())
                        || contact.getFixtureB().getBody().equals(outer_orbit.getBody())) {
                    Body outer;
                    if (contact.getFixtureA().getBody().equals(outer_orbit.getBody())) {
                        outer = contact.getFixtureA().getBody();
                    } else if (contact.getFixtureB().getBody().equals(outer_orbit.getBody())) {
                        outer = contact.getFixtureB().getBody();
                    }

                    if (Vector2.dst(inner_orbit.getPosition().x, inner_orbit.getPosition().y,
                            player.getPosition().x, player.getPosition().y) > inner_orbit.getRadius()) {
                        //System.out.println("GOLDILOCKS!!");
                    }

                }

            }

        }

        @Override
        public void endContact(Contact contact) {
        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
        }

    });
}

From source file:com.pilot51.cannon.GameField.java

License:Apache License

@Override
public Scene onLoadScene() {
    final Scene scene = new Scene(3);
    scene.setBackground(new ColorBackground(Color.red(colorBG) / 255f, Color.green(colorBG) / 255f,
            Color.blue(colorBG) / 255f, Color.alpha(colorBG) / 255f));
    scene.setOnSceneTouchListener(this);
    mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(wind * (float) Math.pow(speed, 2),
            SensorManager.GRAVITY_EARTH * gravity * (float) Math.pow(speed, 2)), false, 3, 2);
    drawGrid(scene);/* ww w .  j  a v  a 2s. c om*/
    final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 0, false);
    if (Common.getPrefs().getBoolean("ground", false)) {
        final Shape ground = new Rectangle(0, -1 / pxPerMeter, cameraWidth / pxPerMeter, 1 / pxPerMeter);
        PhysicsFactory.createBoxBody(mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
        addEntity(ground, 0, scene);
    }
    if (Common.getPrefs().getBoolean("roof", false)) {
        final Shape roof = new Rectangle(0, -cameraHeight / pxPerMeter, cameraWidth / pxPerMeter,
                1 / pxPerMeter);
        PhysicsFactory.createBoxBody(mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
        addEntity(roof, 0, scene);
    }
    if (Common.getPrefs().getBoolean("leftWall", false)) {
        final Shape left = new Rectangle(0, -cameraHeight / pxPerMeter, 1 / pxPerMeter,
                cameraHeight / pxPerMeter);
        PhysicsFactory.createBoxBody(mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
        addEntity(left, 0, scene);
    }
    if (Common.getPrefs().getBoolean("rightWall", false)) {
        final Shape right = new Rectangle((cameraWidth - 1) / pxPerMeter, -cameraHeight / pxPerMeter,
                1 / pxPerMeter, cameraHeight / pxPerMeter);
        PhysicsFactory.createBoxBody(mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);
        addEntity(right, 0, scene);
    }
    if (mRandom || CustomGame.getCustomPrefs().getInt("targetD", 0) > 0
            | CustomGame.getCustomPrefs().getInt("targetH", 0) > 0) {
        addTarget();
        mPhysicsWorld.setContactListener(new ContactListener() {
            public void beginContact(final Contact pContact) {
                final Body bodyA = pContact.getFixtureA().getBody();
                final Body bodyB = pContact.getFixtureB().getBody();
                if ((bodyA == targetBody | bodyB == targetBody) & targetBody.getUserData().equals(true)) {
                    targetBody.setUserData(false);
                    TimerTask targetAction = new TimerTask() {
                        @Override
                        public void run() {
                            if (expTarget)
                                createFirework();
                            if (keepTargets) {
                                target.setColor(Color.red(colorHitTarget) / 255f,
                                        Color.green(colorHitTarget) / 255f, Color.blue(colorHitTarget) / 255f,
                                        Color.alpha(colorHitTarget) / 255f);
                            } else {
                                nTargets--;
                                removeSprite(target, 1);
                            }
                            if (mRandom)
                                addTarget();
                        }
                    };
                    new Timer().schedule(targetAction, (long) (100 / speed));
                    long hits;
                    if (bodyA == targetBody) {
                        @SuppressWarnings("unchecked")
                        HashMap<String, Object> map = ((HashMap<String, Object>) bodyB.getUserData());
                        hits = (Long) map.get("hits") + 1;
                        map.put("hits", hits);
                        bodyB.setUserData(map);
                    } else {
                        @SuppressWarnings("unchecked")
                        HashMap<String, Object> map = ((HashMap<String, Object>) bodyA.getUserData());
                        hits = (Long) map.get("hits") + 1;
                        map.put("hits", hits);
                        bodyA.setUserData(map);
                    }
                    if (mRandom) {
                        if (collide & keepTargets)
                            score += nTargets * hits;
                        else
                            score += hits * 20;
                        if (score > prefScores.getLong(scoreType, 0)) {
                            String txt = getString(R.string.hud_high, score);
                            hText.setPosition(cameraWidth - 10 - txt.length() * fontSize * 0.6f, 40);
                            hText.setText(txt);
                            prefScores.edit().putLong(scoreType, score).commit();
                        }
                        String txt = getString(R.string.hud_score, score);
                        sText.setPosition(cameraWidth - 10 - txt.length() * fontSize * 0.6f, 10);
                        sText.setText(txt);
                    }
                }
            }

            public void endContact(final Contact pContact) {
            }
        });
    }
    scene.registerUpdateHandler(mPhysicsWorld);
    aText = new ChangeableText(10, 10, mFont, getString(R.string.hud_angle, angle),
            getString(R.string.hud_angle, 11111).length());
    addEntity(aText, 0, HUD);
    vText = new ChangeableText(10, 40, mFont, getString(R.string.hud_velocity, velocity),
            getString(R.string.hud_velocity, 11111).length());
    addEntity(vText, 0, HUD);
    if (mRandom) {
        String txt = getString(R.string.hud_score, score);
        sText = new ChangeableText(cameraWidth - 10 - txt.length() * fontSize * 0.6f, 10, mFont, txt, 100);
        addEntity(sText, 0, HUD);
        txt = getString(R.string.hud_high, prefScores.getLong(scoreType, 0));
        hText = new ChangeableText(cameraWidth - 10 - txt.length() * fontSize * 0.6f, 40, mFont, txt, 100);
        addEntity(hText, 0, HUD);
    }
    return scene;
}

From source file:com.sertaogames.cactus2d.Cactus2DLevel.java

License:Open Source License

private void initPhysics() {
    world = new World(new Vector2(0, -25f), true);
    world.setContactListener(new ContactListener() {
        @Override//  www  . j  a va 2  s.c om
        public void beginContact(Contact co) {
            Fixture fa = co.getFixtureA();
            Fixture fb = co.getFixtureB();
            if (fa.isSensor() && fb.isSensor())
                return;

            GameObject a = (GameObject) fa.getBody().getUserData();
            GameObject b = (GameObject) fb.getBody().getUserData();

            if (fa.isSensor() || fb.isSensor()) {
                a.onTriggerEnter(co, b);
                b.onTriggerEnter(co, a);
            } else {
                a.onCollisionEnter(co, b);
                b.onCollisionEnter(co, a);
            }
        }

        @Override
        public void endContact(Contact co) {
            Fixture fa = co.getFixtureA();
            Fixture fb = co.getFixtureB();
            if (fa.isSensor() && fb.isSensor())
                return;

            GameObject a = (GameObject) fa.getBody().getUserData();
            GameObject b = (GameObject) fb.getBody().getUserData();

            if (fa.isSensor() || fb.isSensor()) {
                a.onTriggerExit(co, b);
                b.onTriggerExit(co, a);
            } else {
                a.onCollisionExit(co, b);
                b.onCollisionExit(co, a);
            }
        }

        @Override
        public void preSolve(Contact points, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact co, ContactImpulse impulse) {
            Fixture fa = co.getFixtureA();
            Fixture fb = co.getFixtureB();
            if (fa.isSensor() && fb.isSensor())
                return;

            GameObject a = (GameObject) fa.getBody().getUserData();
            GameObject b = (GameObject) fb.getBody().getUserData();

            if (fa.isSensor() || fb.isSensor()) {
                a.onTriggerStay(co, b);
                b.onTriggerStay(co, a);
            } else {
                a.onCollisionStay(co, b);
                b.onCollisionStay(co, a);
            }
        }
    });
}

From source file:com.thirdgame.shootkillninjabomb.GameLayer.java

License:Open Source License

private ContactListener createContactListener() {
    ContactListener contactListener = new ContactListener() {

        @Override/*w  w  w .  ja v  a  2 s .  c  om*/
        public void beginContact(final Contact pContact) {

            final Fixture fixtureA = pContact.getFixtureA();
            final Fixture fixtureB = pContact.getFixtureB();

            final Body bodyA = fixtureA.getBody();
            final Body bodyB = fixtureB.getBody();

            final UserData userDataA = (UserData) bodyA.getUserData();
            final UserData userDataB = (UserData) bodyB.getUserData();

            if (userDataA == null || userDataB == null) {
                return;
            }
            isTouch = false;
            isWallsTouch = 0;
            if ((userDataA.type == "Floor" && userDataB.type == "Shape")
                    || (userDataB.type == "Floor" && userDataA.type == "Shape")) {
                i = 1;
                isWallsTouch = 1;
                if (userDataA.type == "Floor") {
                    //      bodyB.setActive(false);
                    userDataB.type = "Remove";
                    if (GameScene.gameScene.countLives() > 1)
                        GameScene.gameScene.setGameOver();
                } else {
                    //      bodyA.setActive(false);
                    userDataA.type = "Remove";
                    if (GameScene.gameScene.countLives() > 1)
                        GameScene.gameScene.setGameOver();
                }
            }
            if (((userDataA.type == "Floor" || userDataA.type == "Wall") && userDataB.type == "Bullet")
                    || ((userDataB.type == "Floor" || userDataB.type == "Wall")
                            && userDataA.type == "Bullet")) {

                if (userDataA.type == "Bullet") {
                    userDataA.type = "Remove";
                    if (userDataA.count > 0)
                        GameScene.gameScene.setBulletHitCount();
                    if (userDataA.count < 2) {
                        isWallsTouch = 1;
                        mComboCount = 0;
                    }
                    if (mComboCount > 1 && userDataA.count > 1) {
                        touchCount += (mComboCount - 1) * 4;
                        mGameScene.fireComboParticle(mComboCount - 1);
                    }
                } else {
                    if (userDataB.count < 2) {
                        mComboCount = 0;
                        isWallsTouch = 1;
                    }
                    if (userDataB.count > 0)
                        GameScene.gameScene.setBulletHitCount();
                    if (mComboCount > 1 && userDataB.count > 1) {
                        touchCount += (mComboCount - 1) * 4;
                        mGameScene.fireComboParticle(mComboCount - 1);
                    }
                    userDataB.type = "Remove";
                }

            }
            if ((userDataA.eggType == "redyellowegg" || userDataB.eggType == "redyellowegg")
                    && (userDataA.type == "Bullet" || userDataB.type == "Bullet")) {

                isTouch = true;
                //   mGameScene.setScore(120);
                mGameScene.fireParticle(fixtureA);
                i = 1;
                isWallsTouch = 2;
            }
            if ((userDataA.eggType == "brownskyblueegg" || userDataB.eggType == "brownskyblueegg")
                    && (userDataA.type == "Bullet" || userDataB.type == "Bullet")) {
                isTouch = true;
                isWallsTouch = 2;
                //   mGameScene.setScore(900);
                mGameScene.fireParticleOne(fixtureA);
                i = 1;
            }
            if ((userDataA.eggType == "orangeeyellowegg" || userDataB.eggType == "orangeeyellowegg")
                    && (userDataA.type == "Bullet" || userDataB.type == "Bullet")) {
                isTouch = true;
                isWallsTouch = 2;
                mGameScene.fireParticleTwo(fixtureA);
                i = 1;
                //   mGameScene.setScore(550);
            }
            if ((userDataA.eggType == "blueeegreenegg" || userDataB.eggType == "blueeegreenegg")
                    && (userDataA.type == "Bullet" || userDataB.type == "Bullet")) {
                isTouch = true;
                isWallsTouch = 2;
                mGameScene.fireParticleThree(fixtureA);
                i = 1;
            }
            if ((userDataA.eggType == "newblueyellow" || userDataB.eggType == "newblueyellow")
                    && (userDataA.type == "Bullet" || userDataB.type == "Bullet")) {
                isTouch = true;
                isWallsTouch = 2;
                mGameScene.fireParticleFour(fixtureA);
                i = 1;
                getAudioPlayer().play(SoundKeys.MULTIPLIER);
            }
            if ((userDataA.eggType == "newblueredegg" || userDataB.eggType == "newblueredegg")
                    && (userDataA.type == "Bullet" || userDataB.type == "Bullet")) {
                isTouch = true;
                isWallsTouch = 2;
                mGameScene.fireParticleFive(fixtureA);
                i = 1;
                getAudioPlayer().play(SoundKeys.FREEZE);
            }

            if (i == 1 && isWallsTouch == 2) {
                multiplier = 1;
                if (GameScene.gameScene.getMultiplier())
                    multiplier = 2;
                touchCount += multiplier;

            }

            if (isTouch) {
                if (userDataA.type == "Shape") {
                    userDataB.count++;
                    userDataA.type = "Remove";
                    if (userDataB.count == 2) {
                        touchCount += 2 * multiplier;
                        mComboCount++;
                        mGameScene.fireBonusParticle(1, fixtureA);
                        getAudioPlayer().play(SoundKeys.DOUBLE);
                    } else if (userDataB.count == 3) {
                        touchCount += 3 * multiplier;
                        mGameScene.fireBonusParticle(2, fixtureA);
                        getAudioPlayer().play(SoundKeys.DOUBLE);
                    } else if (userDataA.isCritical) {
                        touchCount += 5;
                        mGameScene.fireBonusParticle(3, fixtureA);
                        getAudioPlayer().play(SoundKeys.DOUBLE);
                    }
                } else {
                    userDataA.count++;
                    userDataB.type = "Remove";
                    if (userDataA.count == 2) {
                        touchCount += 2 * multiplier;
                        mComboCount++;
                        mGameScene.fireBonusParticle(1, fixtureA);
                        getAudioPlayer().play(SoundKeys.DOUBLE);
                    } else if (userDataA.count == 3) {
                        touchCount += 3 * multiplier;
                        mGameScene.fireBonusParticle(2, fixtureA);
                        getAudioPlayer().play(SoundKeys.DOUBLE);
                    } else if (userDataB.isCritical) {
                        touchCount += 5;
                        mGameScene.fireBonusParticle(3, fixtureA);
                        getAudioPlayer().play(SoundKeys.DOUBLE);
                    }
                }

                if (i == 1) {

                    mGameScene.setScore(touchCount);
                    getAudioPlayer().play(SoundKeys.EGG_BREAK);
                }

            }

            //   mGameScene.cleanObjectList();
            runOnUpdateThread(new Runnable() {

                @Override
                public void run() {
                    switch (i) {
                    case 1:
                        mGameScene.cleanObjectList();
                        break;

                    default:
                        break;
                    }
                }
            });

        }

        @Override
        public void endContact(Contact contact) {
            // TODO Auto-generated method stub

        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
            // TODO Auto-generated method stub

            final Fixture fixtureA = contact.getFixtureA();
            final Fixture fixtureB = contact.getFixtureB();
            UserData uA = (UserData) fixtureA.getBody().getUserData();
            UserData uB = (UserData) fixtureB.getBody().getUserData();
            if ((uB.type == "Bullet") || (uA.type == "Bullet"))
                contact.setEnabled(false);
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            // TODO Auto-generated method stub

        }
    };
    return contactListener;
    /* Collision of a hen with the floor. */
    /*   if (CollisionListener.isExpectedContact(userDataA.getObjectName(), userDataB.getObjectName(),
    Names.FlyingHenName, Names.FloorName)
    || CollisionListener.isExpectedContact(userDataA.getObjectName(), userDataB.getObjectName(),
          Names.FlyingBombName, Names.FloorName)
    || CollisionListener.isExpectedContact(userDataA.getObjectName(), userDataB.getObjectName(),
          Names.FlyingThunderboltName, Names.FloorName)) {
          // TODO: Check with bomb.
          getAudioPlayer().play(SoundKeys.BOUNCE);
            
          final IBullet bullet = userDataA.getObjectName().equals(Names.FlyingHenName) ? (IBullet) userDataA
       : (IBullet) userDataB;
            
          mGunLayer.onCollision(bullet);
            
       } else if (collisionWithRoofOrWalls(userDataA.getObjectName(), userDataB.getObjectName())) {
          getAudioPlayer().play(SoundKeys.BOUNCE);
          /* Collision of a hen with the hen top. */
    /*   } else if (CollisionListener.isExpectedContact(userDataA.getObjectName(), userDataB.getObjectName(),
    Names.FlyingHenName, Names.HenName)) {
          getAudioPlayer().play(SoundKeys.CONNECTION);
            
          runOnUpdateThread(new Runnable() {
            
    @Override
    public void run() {
       mGunLayer.resetGunLayerAfterConnectedBulletOrTimeElapsed(true);
    }
          });
          mHenLayer.onCollision(pContact);
            
          /* Collision of a bomb with the hen top. */
    /*   } else if (CollisionListener.isExpectedContact(userDataA.getObjectName(), userDataB.getObjectName(),
    Names.FlyingBombName, Names.HenName)
    || CollisionListener.isExpectedContact(userDataA.getObjectName(), userDataB.getObjectName(),
          Names.FlyingThunderboltName, Names.HenName)) {
          final IBullet bullet;
          if (Names.FlyingBombName.equals(userDataA.getObjectName())
       || Names.FlyingThunderboltName.equals(userDataA.getObjectName())) {
    bullet = (IBullet) userDataA;
          } else {
    bullet = (IBullet) userDataB;
          }
            
          bullet.setBodyType(BodyType.StaticBody);
          final AnimatedSpriteWithAreaToTouch animatedSpriteWithAreaToTouch = bullet
       .getAnimatedSpriteWithAreaToTouch();
          final long[] tabOfAnimations = new long[] { 100, 100, 100 };
          final float xPosition = animatedSpriteWithAreaToTouch.getX();
          final float yPosition = animatedSpriteWithAreaToTouch.getY();
          mEffectsLayer.prepareBombExplosion(xPosition, yPosition);
          animatedSpriteWithAreaToTouch.animate(tabOfAnimations, 3, 5, false, new OnAnimationFinishedListener(
       new IOnAnimationFinishedListener() {
          @Override
          public void onAnimationFinished(final AnimatedSprite pAnimatedSprite) {
             runOnUpdateThread(new Runnable() {
            
                @Override
                public void run() {
                   if (bullet.getBulletType() == BulletType.THUNDERBOLT) {
                      getAudioPlayer().play(SoundKeys.THUNDER);
                   } else {
                      getAudioPlayer().play(SoundKeys.BOMB_EXPLOSION);
                   }
            
                   if (bullet.getBulletType() == BulletType.BOMB) {
                      mEffectsLayer.explodeBullet();
                   }
                   mHenLayer.onCollisionWithBullet(pContact);
                   animatedSpriteWithAreaToTouch.detachSelf();
                   final PhysicsWorld pw = getPhysicsWorld();
                   final PhysicsConnector mPhysicsConnector = pw.getPhysicsConnectorManager()
                         .findPhysicsConnectorByShape(animatedSpriteWithAreaToTouch);
                   if (mPhysicsConnector != null) {
                      pw.unregisterPhysicsConnector(mPhysicsConnector);
                      final Body b = mPhysicsConnector.getBody();
                      pw.destroyBody(b);
                   }
                   mGunLayer.resetGunLayerAfterConnectedBulletOrTimeElapsed(true);
                }
             });
          }
       }));
       }*/
}

From source file:com.uwsoft.editor.gdx.ui.components.ItemPhysicsEditor.java

License:Apache License

public void startTest() {
    if (minPolies == null) {
        return;//from  w  ww.  ja  va2 s.  c om
    }
    testBodiesToDestroy.clear();
    MeshVO vo = new MeshVO();
    vo.minPolygonData = minPolies;
    physicsEditorWorld = new World(new Vector2(0, -10), true);
    physicsEditorWorld.setContactListener(new ContactListener() {
        @Override
        public void beginContact(Contact contact) {
        }

        @Override
        public void endContact(Contact contact) {

        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            if (edgBodyList.indexOf(contact.getFixtureA().getBody()) != -1) {
                testBodiesToDestroy.add(contact.getFixtureB().getBody());
            }
            if (edgBodyList.indexOf(contact.getFixtureB().getBody()) != -1) {
                testBodiesToDestroy.add(contact.getFixtureA().getBody());
            }
        }
    });
    currentItemBody = PhysicsBodyLoader.createBody(physicsEditorWorld, physicsBodyDataVO, vo,
            new Vector2(1, 1));
    //
    crateEdgPlatform(0, 0, getWidth(), 0);
    crateEdgPlatform(0, 0, 0, getHeight());
    crateEdgPlatform(getWidth(), 0, 0, getHeight());
    crateEdgPlatform(0, getHeight(), getWidth(), 0);

    currentMode = EditMode.Test;
    nearestPoint.unSet();
    selectedPoint.unSet();
    lineIndex = -1;
}

From source file:edu.lehigh.cse.lol.Physics.java

License:Open Source License

/**
 * Configure physics for the current level
 *
 * @param defaultXGravity The default force moving actors to the left (negative) or
 *                        right (positive)... Usually zero
 * @param defaultYGravity The default force pushing actors down (negative) or up
 *                        (positive)... Usually zero or -10
 *//*ww  w  . j av  a2s  . c  o  m*/
public static void configure(float defaultXGravity, float defaultYGravity) {
    // create a world with gravity
    Lol.sGame.mCurrentLevel.mWorld = new World(new Vector2(defaultXGravity, defaultYGravity), true);

    // set up the collision handlers
    Lol.sGame.mCurrentLevel.mWorld.setContactListener(new ContactListener() {
        /**
         * When two bodies start to collide, we can use this to forward to
         * our onCollide methods
         */
        @Override
        public void beginContact(final Contact contact) {
            // Get the bodies, make sure both are actors
            Object a = contact.getFixtureA().getBody().getUserData();
            Object b = contact.getFixtureB().getBody().getUserData();
            if (!(a instanceof Actor) || !(b instanceof Actor))
                return;

            // the order is Hero, Enemy, Goodie, Projectile, Obstacle, Destination
            //
            // Of those, Hero, Enemy, and Projectile are the only ones with
            // a non-empty onCollide
            final Actor c0;
            final Actor c1;
            if (a instanceof Hero) {
                c0 = (Actor) a;
                c1 = (Actor) b;
            } else if (b instanceof Hero) {
                c0 = (Actor) b;
                c1 = (Actor) a;
            } else if (a instanceof Enemy) {
                c0 = (Actor) a;
                c1 = (Actor) b;
            } else if (b instanceof Enemy) {
                c0 = (Actor) b;
                c1 = (Actor) a;
            } else if (a instanceof Projectile) {
                c0 = (Actor) a;
                c1 = (Actor) b;
            } else if (b instanceof Projectile) {
                c0 = (Actor) b;
                c1 = (Actor) a;
            } else {
                return;
            }

            // Schedule an event to run as soon as the physics world
            // finishes its step.
            //
            // NB: this is called from render, while world is updating...
            // you can't modify the world or its actors until the update
            // finishes, so we have to schedule collision-based updates to
            // run after the world update.
            Lol.sGame.mCurrentLevel.mOneTimeEvents.add(new LolAction() {
                @Override
                public void go() {
                    c0.onCollide(c1, contact);
                }
            });
        }

        /**
         * We ignore endcontact
         */
        @Override
        public void endContact(Contact contact) {
        }

        /**
         * Presolve is a hook for disabling certain collisions. We use it
         * for collision immunity, sticky obstacles, and one-way walls
         */
        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
            // get the bodies, make sure both are actors
            Object a = contact.getFixtureA().getBody().getUserData();
            Object b = contact.getFixtureB().getBody().getUserData();
            if (!(a instanceof Actor) || !(b instanceof Actor))
                return;
            Actor gfoA = (Actor) a;
            Actor gfoB = (Actor) b;

            // handle sticky obstacles... only do something if at least one
            // actor is a sticky actor
            if (gfoA.mIsSticky[0] || gfoA.mIsSticky[1] || gfoA.mIsSticky[2] || gfoA.mIsSticky[3]) {
                handleSticky(gfoA, gfoB, contact);
                return;
            } else if (gfoB.mIsSticky[0] || gfoB.mIsSticky[1] || gfoB.mIsSticky[2] || gfoB.mIsSticky[3]) {
                handleSticky(gfoB, gfoA, contact);
                return;
            }

            // if the actors have the same passthrough ID, and it's
            // not zero, then disable the contact
            if (gfoA.mPassThroughId != 0 && gfoA.mPassThroughId == gfoB.mPassThroughId) {
                contact.setEnabled(false);
                return;
            }

            // is either one-sided? If not, we're done
            Actor onesided = null;
            Actor other;
            if (gfoA.mIsOneSided > -1) {
                onesided = gfoA;
                other = gfoB;
            } else if (gfoB.mIsOneSided > -1) {
                onesided = gfoB;
                other = gfoA;
            } else {
                return;
            }

            // if we're here, see if we should be disabling a one-sided
            // obstacle collision
            WorldManifold worldManiFold = contact.getWorldManifold();
            int numPoints = worldManiFold.getNumberOfContactPoints();
            for (int i = 0; i < numPoints; i++) {
                Vector2 vector2 = other.mBody.getLinearVelocityFromWorldPoint(worldManiFold.getPoints()[i]);
                // disable based on the value of isOneSided and the vector
                // between the actors
                if (onesided.mIsOneSided == 0 && vector2.y < 0)
                    contact.setEnabled(false);
                else if (onesided.mIsOneSided == 2 && vector2.y > 0)
                    contact.setEnabled(false);
                else if (onesided.mIsOneSided == 1 && vector2.x > 0)
                    contact.setEnabled(false);
                else if (onesided.mIsOneSided == 3 && vector2.x < 0)
                    contact.setEnabled(false);
            }
        }

        /**
         * We ignore postsolve
         */
        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
        }
    });
}

From source file:me.scarlet.undertailor.collision.CollisionHandler.java

License:Open Source License

public void reset() {
    this.timeAccumulator = 0F;
    this.world = new World(new Vector2(0F, 0F), true);
    this.world.setContactListener(new ContactListener() {

        @Override/* w  w  w. j  a  v a2 s.  c om*/
        public void preSolve(Contact contact, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
        }

        @Override
        public void endContact(Contact contact) {
            Object uda = contact.getFixtureA().getBody().getUserData();
            Object udb = contact.getFixtureB().getBody().getUserData();
            if (uda instanceof Collider && udb instanceof Collider) {
                ((Collider) uda).getContacts().remove(udb);
                ((Collider) udb).getContacts().remove(uda);
            }
        }

        @Override
        public void beginContact(Contact contact) {
            Object uda = contact.getFixtureA().getBody().getUserData();
            Object udb = contact.getFixtureB().getBody().getUserData();
            if (uda instanceof Collider && udb instanceof Collider) {
                ((Collider) uda).getContacts().add((Collider) udb);
                ((Collider) udb).getContacts().add((Collider) uda);
            }
        }
    });
}