void onGameStart(Nothing ignored) throws InterruptedException {
      System.out.println("Physics: on game start");
      if (world != null) world.dispose();
      world = new World(new Vector2(0, Constants.WORLD_GRAVITY), true);

      world.setContactListener(new HitTester((isOnGround) -> isPlayerOnFloor = isOnGround));

      _createPlayer();

      state = GameState.IN_GAME;
    }
  public Play(GameStateManager gsm) {
    super(gsm);

    // Create box2d world and debugger and apply custom contact listener
    world = new World(new Vector2(0, -9.81f), true);
    cl = new MyContactListener();
    world.setContactListener(cl);
    b2dr = new Box2DDebugRenderer();

    // Creates player box2d object with foot sensor
    createPlayer();

    // Loads the tiled map
    loadTiles();

    // generates box2d platforms from the tiles in the given layer
    generatePlatforms("Collidables");

    // create coins
    createCoins();
  }
Exemple #3
0
  @Override
  public void create() {
    stop = win = false;

    debugRenderer = new Box2DDebugRenderer();
    Gdx.input.setInputProcessor(new PlayerInputProcessor(player));
    camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cameraBak = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    batch = new SpriteBatch();
    atlas = new TextureAtlas("spacemangame.atlas");

    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(new FileHandle("font.ttf"));
    FreeTypeFontGenerator.FreeTypeFontParameter parameter =
        new FreeTypeFontGenerator.FreeTypeFontParameter();
    parameter.size = 120;
    font = generator.generateFont(parameter); // font size 12 pixels
    generator.dispose();

    layout = new GlyphLayout();
    b2dWorld = new World(new Vector2(0, -0.8f), true);
    b2dWorld.setContactListener(new GameCollision());

    player = new Player(atlas, b2dWorld, -200, camera.viewportHeight / 2 - 30, 1, 10000);

    meter = new SimpleGameObject(atlas, "meter", -camera.viewportWidth / 2 + 45, -120);
    meter_fuel = new SimpleGameObject(atlas, "meter_fuel", -camera.viewportWidth / 2 + 52, -159);
    lives = new SimpleGameObject(atlas, "spaceman_jump1", -camera.viewportWidth / 2 + 20, 200);
    gameOver = new SimpleGameObject(atlas, "game_over", -80, -70);
    meter.sprite.scale(2);
    meter_fuel.sprite.scale(2);
    gameOver.sprite.scale(2);
    background = new Background(atlas, -120, -80);

    manager = new GameObjectManager(atlas, b2dWorld, player, camera);
    manager.loadGameFromFile("level.png");
  }
 public void setContactListener(ContactListener listener) {
   world.setContactListener(listener);
 }
  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(
              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) {}
        });
  }
  public void Create() {
    // set tilemap file name
    m_MapFileName = "map/test.tmx";

    // set up the tilemap
    m_TiledMap = new TmxMapLoader().load(m_MapFileName);
    m_TiledMapRenderer = new OrthogonalTiledMapRenderer(m_TiledMap, 1f);

    // set up the box2d physics
    m_PhysicsWorld = new com.badlogic.gdx.physics.box2d.World(new Vector2(0, 0), true);

    // attach contact listener to physics world
    m_PhysicsWorld.setContactListener(new GameContactListener(this));

    // set up box2dlights
    m_RayHandler = new RayHandler(m_PhysicsWorld);
    m_RayHandler.setAmbientLight(0.0f);

    // add tilemap collision boxes to physics world
    for (int i = 0; i < m_TiledMap.getLayers().getCount(); i++) {
      if (m_TiledMap.getLayers().get(i) instanceof TiledMapTileLayer) {
        TiledMapTileLayer layer = (TiledMapTileLayer) m_TiledMap.getLayers().get(i);
        for (int j = 0; j < layer.getWidth(); j++) {
          for (int k = 0; k < layer.getHeight(); k++) {
            Cell cell = layer.getCell(j, k);
            if (cell != null) {
              TiledMapTile tile = cell.getTile();
              if (tile != null) {
                MapProperties props = tile.getProperties();
                if (props.containsKey("blocked")) {
                  float worldX = j * 64 + 32;
                  float worldY = k * 64 + 32;
                  BodyDef bodyDef = new BodyDef();
                  bodyDef.type = BodyType.StaticBody;
                  bodyDef.position.set(new Vector2(worldX * WORLD_TO_BOX, worldY * WORLD_TO_BOX));

                  Body newBody = m_PhysicsWorld.createBody(bodyDef);

                  PolygonShape boxShape = new PolygonShape();
                  boxShape.setAsBox(32 * WORLD_TO_BOX, 32 * WORLD_TO_BOX);

                  // Create a fixture definition to apply our shape to
                  FixtureDef fixtureDef = new FixtureDef();
                  fixtureDef.shape = boxShape;

                  newBody.createFixture(fixtureDef);

                  boxShape.dispose();
                }

                if (props.containsKey("rotate")) {
                  // flip some random tiles to break pattern
                  if (k * j % 3 == 0) layer.getCell(j, k).setFlipVertically(true);
                  if (k * j % 2 == 0) layer.getCell(j, k).setFlipHorizontally(true);
                }
              }
            }
          }
        }
      }
    }

    // set up artemis entity system
    m_ArtemisWorld = new com.artemis.World();

    // add the passive systems
    m_SpineRenderSystem = new SpineRenderSystem(m_GameScreen);
    m_ArtemisWorld.setSystem(m_SpineRenderSystem, true);

    // add the systems
    m_ArtemisWorld.setSystem(new PlayerInputSystem(this));
    m_ArtemisWorld.setSystem(new CameraSystem(m_GameScreen.m_Camera));
    m_ArtemisWorld.setSystem(new PhysicsSystem());
    m_ArtemisWorld.setSystem(new LifecycleSystem(this));
    m_ArtemisWorld.setSystem(new SteeringSystem());

    // init the world
    m_ArtemisWorld.initialize();
    EntityHelper.LoadObjects(
        m_GameScreen, m_ArtemisWorld, m_TiledMap, m_PhysicsWorld, m_RayHandler);

    // add player to entity list
    m_PlayerEntity = new PlayerEntity();
    m_PlayerEntity.AddToWorld(this);
    checkpointPos = new Vector2(0, 0);
    checkpointPos.x = m_PlayerEntity.m_Entity.getComponent(PositionComponent.class).m_X;
    checkpointPos.y = m_PlayerEntity.m_Entity.getComponent(PositionComponent.class).m_Y;

    // hud items are special cases since they needs to draw on top of border
    m_VialOne = new SpineComponent("map/vial", 5, 0.75f, -25);
    m_VialTwo = new SpineComponent("map/vial", 5, 0.65f, -5);
    m_VialThree = new SpineComponent("map/vial", 5, 0.75f, -50);
    m_WatchSpine = new SpineComponent("map/watch", 4, 0.75f, 0);

    if (m_GameScreen.m_Settings.m_WatchFound) {
      ActivateWatch();
      BodyComponent bodyComponent = m_PlayerEntity.m_Entity.getComponent(BodyComponent.class);
      bodyComponent.m_Body.setTransform(621 * WORLD_TO_BOX, 5961 * WORLD_TO_BOX, 0);
    }
    if (m_GameScreen.m_Settings.m_WeaponFound) {
      ActivateSword();
      BodyComponent bodyComponent = m_PlayerEntity.m_Entity.getComponent(BodyComponent.class);
      bodyComponent.m_Body.setTransform(1965 * WORLD_TO_BOX, 4842 * WORLD_TO_BOX, 0);
    }
    if (m_GameScreen.m_Settings.m_WeaponLightFound) {
      ActivateSwordLight();
      BodyComponent bodyComponent = m_PlayerEntity.m_Entity.getComponent(BodyComponent.class);
      bodyComponent.m_Body.setTransform(6390 * WORLD_TO_BOX, 6462 * WORLD_TO_BOX, 0);
    }
  }
  @Override
  public void create() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    bitmapFont = new BitmapFont(Gdx.files.internal("data/arial-15.fnt"), false);

    Gdx.input.setInputProcessor(this);

    mCamPos = new Vector3();
    mCurrentPos = new Vector3();

    camera = new OrthographicCamera(100, 100 * h / w);
    camera.position.set(50, 50, 0);
    camera.zoom = 1.8f;
    camera.update();

    textCam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    textCam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
    textCam.zoom = 1;
    textCam.update();

    loader = new RubeSceneLoader();

    scene = loader.loadScene(Gdx.files.internal("data/palm.json"));

    debugRender = new Box2DDebugRenderer();

    batch = new SpriteBatch();
    polygonBatch = new PolygonSpriteBatch();

    textureMap = new HashMap<String, Texture>();
    textureRegionMap = new HashMap<Texture, TextureRegion>();

    createSpatialsFromRubeImages(scene);
    createPolySpatialsFromRubeFixtures(scene);

    mWorld = scene.getWorld();
    // configure simulation settings
    mVelocityIter = scene.velocityIterations;
    mPositionIter = scene.positionIterations;
    if (scene.stepsPerSecond != 0) {
      mSecondsPerStep = 1f / scene.stepsPerSecond;
    }
    mWorld.setContactListener(this);
    //
    // example of custom property handling
    //
    Array<Body> bodies = scene.getBodies();
    if ((bodies != null) && (bodies.size > 0)) {
      for (int i = 0; i < bodies.size; i++) {
        Body body = bodies.get(i);
        String gameInfo = (String) scene.getCustom(body, "GameInfo", null);
        if (gameInfo != null) {
          System.out.println("GameInfo custom property: " + gameInfo);
        }
      }
    }

    // Example of accessing data based on name
    System.out.println("body0 count: " + scene.getNamed(Body.class, "body0").size);
    // Note: the scene has two fixture9 names defined, but these are in turn subdivided into
    // multiple fixtures and thus appear several times...
    System.out.println("fixture9 count: " + scene.getNamed(Fixture.class, "fixture9").size);
    scene.printStats();

    //
    // validate the custom settings attached to world object..
    //
    boolean testBool = (Boolean) scene.getCustom(mWorld, "testCustomBool", false);
    int testInt = (Integer) scene.getCustom(mWorld, "testCustomInt", 0);
    float testFloat = (Float) scene.getCustom(mWorld, "testCustomFloat", 0);
    Color color = (Color) scene.getCustom(mWorld, "testCustomColor", null);
    Vector2 vec = (Vector2) scene.getCustom(mWorld, "testCustomVec2", null);
    String string = (String) scene.getCustom(mWorld, "testCustomString", null);

    if (testBool == false) {
      throw new GdxRuntimeException(
          "testCustomBool not read correctly! Expected: " + true + " Actual: " + testBool);
    }
    if (testInt != 8675309) {
      throw new GdxRuntimeException(
          "testCustomInt not read correctly! Expected: " + 8675309 + " Actual: " + testInt);
    }
    if (testFloat != 1.25f) {
      throw new GdxRuntimeException(
          "testCustomFloat not read correctly! Expected: " + 1.25f + " Actual: " + testFloat);
    }
    if (color == null) {
      throw new GdxRuntimeException("testCustomColor is reporting null!");
    }
    if ((color.r != 17f / 255)
        || (color.g != 29f / 255)
        || (color.b != 43f / 255)
        || (color.a != 61f / 255)) {
      throw new GdxRuntimeException(
          "testCustomColor not read correctly!  Expected: "
              + new Color(17f / 255, 29f / 255, 43f / 255, 61f / 255)
              + " Actual: "
              + color);
    }
    if (vec == null) {
      throw new GdxRuntimeException("testCustomVec2 is reporting null!");
    }
    if ((vec.x != 314159) || (vec.y != 21718)) {
      throw new GdxRuntimeException(
          "testCustomVec2 is not read correctly!  Expected: "
              + new Vector2(314159, 21718)
              + " Actual: "
              + vec);
    }
    if (string == null) {
      throw new GdxRuntimeException("testCustomString is reporting null!");
    }
    if (!string.equalsIgnoreCase("excelsior!")) {
      throw new GdxRuntimeException(
          "testCustomString is not read correctly!  Expected: Excelsior! Actual: " + string);
    }
    scene.clear(); // no longer need any scene references
  }
  @Override
  public void create() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    Gdx.input.setInputProcessor(this);

    mB2Controllers = new Array<B2Controller>();

    mCamPos = new Vector3();
    mCurrentPos = new Vector3();

    camera = new OrthographicCamera(100, 100 * h / w);
    camera.position.set(50, 50, 0);
    camera.zoom = 1.8f;
    camera.update();

    loader = new RubeSceneLoader();

    scene = loader.loadScene(Gdx.files.internal("data/palmcontrollers.json"));

    debugRender = new Box2DDebugRenderer();

    batch = new SpriteBatch();
    polygonBatch = new PolygonSpriteBatch();

    textureMap = new HashMap<String, Texture>();
    textureRegionMap = new HashMap<Texture, TextureRegion>();

    createSpatialsFromRubeImages(scene);
    createPolySpatialsFromRubeFixtures(scene);

    mWorld = scene.getWorld();
    // configure simulation settings
    mVelocityIter = scene.velocityIterations;
    mPositionIter = scene.positionIterations;
    if (scene.stepsPerSecond != 0) {
      mSecondsPerStep = 1f / scene.stepsPerSecond;
    }
    mWorld.setContactListener(this);

    //
    // example of custom property handling
    //
    Array<Body> bodies = scene.getBodies();
    if ((bodies != null) && (bodies.size > 0)) {
      for (int i = 0; i < bodies.size; i++) {
        Body body = bodies.get(i);
        String gameInfo = (String) scene.getCustom(body, "GameInfo", null);
        if (gameInfo != null) {
          System.out.println("GameInfo custom property: " + gameInfo);
        }
      }
    }

    // Instantiate any controllers that are in the scene
    Array<Fixture> fixtures = scene.getFixtures();
    if ((fixtures != null) && (fixtures.size > 0)) {
      for (int i = 0; i < fixtures.size; i++) {
        Fixture fixture = fixtures.get(i);
        int controllerType = (Integer) scene.getCustom(fixture, "ControllerType", 0);
        switch (controllerType) {
          case B2Controller.BUOYANCY_CONTROLLER:
            // only allow polygon buoyancy controllers for now..
            if (fixture.getShape().getType() == Shape.Type.Polygon) {
              float bodyHeight = fixture.getBody().getPosition().y;
              // B2BuoyancyController b2c = new B2BuoyancyController();

              // need to calculate the fluid surface height for the buoyancy controller
              PolygonShape shape = (PolygonShape) fixture.getShape();
              shape.getVertex(0, mTmp);
              float maxHeight =
                  mTmp.y + bodyHeight; // initialize the height, transforming to 'world'
              // coordinates

              // find the maxHeight
              for (int j = 1; j < shape.getVertexCount(); j++) {
                shape.getVertex(j, mTmp);
                maxHeight =
                    Math.max(maxHeight, mTmp.y + bodyHeight); // transform to world coordinates
              }
              B2BuoyancyController b2c =
                  new B2BuoyancyController(
                      B2BuoyancyController.DEFAULT_SURFACE_NORMAL, // assume up
                      (Vector2)
                          scene.getCustom(
                              fixture,
                              "ControllerVelocity",
                              B2BuoyancyController.DEFAULT_FLUID_VELOCITY),
                      mWorld.getGravity(),
                      maxHeight,
                      fixture.getDensity(),
                      (Float)
                          scene.getCustom(
                              fixture, "LinearDrag", B2BuoyancyController.DEFAULT_LINEAR_DRAG),
                      (Float)
                          scene.getCustom(
                              fixture, "AngularDrag", B2BuoyancyController.DEFAULT_ANGULAR_DRAG));
              fixture.setUserData(b2c); // reference back to the controller from the fixture (see
              // beginContact/endContact)
              mB2Controllers.add(b2c); // add it to the list so it can be stepped later
            }
            break;

          case B2Controller.GRAVITY_CONTROLLER:
            {
              B2GravityController b2c = new B2GravityController();
              b2c =
                  new B2GravityController(
                      (Vector2)
                          scene.getCustom(
                              fixture, "ControllerVelocity", B2GravityController.DEFAULT_GRAVITY));
              fixture.setUserData(b2c);
              mB2Controllers.add(b2c);
            }
            break;
        }
      }
    }
    scene.printStats();
    scene.clear(); // no longer need any scene references
  }
 public void setContactListener(ContactListener listener) {
   gameWorldPhysics.setContactListener(listener);
 }
Exemple #10
0
  public PhysicsWorld(
      Vector2 gravityVector, boolean sleepingObjects, boolean enableDebugRendering) {
    world_ = new World(gravityVector, sleepingObjects);
    if (enableDebugRendering) {
      debugRenderer_ = new Box2DDebugRenderer();
      debugRenderingEnabled_ = true;
    }

    world_.setContactListener(
        new ContactListener() {
          @Override
          public void beginContact(Contact contact) {
            Fixture fixA = contact.getFixtureA();
            Fixture fixB = contact.getFixtureB();
            switch (fixA.getFilterData().categoryBits) {
              case SENSOR_NAVIGATION:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {
                  DynamicMonster monster = (DynamicMonster) fixB.getBody().getUserData();
                  Vector2 newTarget = (Vector2) fixA.getUserData();
                  monster.setTarget(newTarget);
                }
                break;
              case SENSOR_GOAL:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {
                  DynamicMonster monster = (DynamicMonster) fixB.getBody().getUserData();
                  monster.timeOfDeath = TimeUtils.millis();
                  monster.isAlive = false;
                }
                break;
              case ENTITY_ENEMY:
                DynamicMonster monster = (DynamicMonster) fixA.getBody().getUserData();
                if (fixB.getFilterData().categoryBits == SENSOR_NAVIGATION) {
                  Vector2 newTarget = (Vector2) fixB.getUserData();
                  monster.setTarget(newTarget);
                } else if (fixB.getFilterData().categoryBits == SENSOR_GOAL) {
                  monster.timeOfDeath = TimeUtils.millis();
                  monster.isAlive = false;
                } else if (fixB.getFilterData().categoryBits == ENTITY_DEFENDER_SPOTTING_SENSOR) {
                  DynamicDefender defender = (DynamicDefender) fixB.getBody().getUserData();
                  defender.EnemyEnteredSpotRange(fixA.getBody());
                } else if (fixB.getFilterData().categoryBits == ENTITY_DEFENDER_FIRE_SENSOR) {
                  DynamicDefender defender = (DynamicDefender) fixB.getBody().getUserData();
                  defender.EnemyEnteredFireRange(fixA.getBody());
                }
                break;
              case ENTITY_DEFENDER_SPOTTING_SENSOR:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {
                  DynamicDefender defender = (DynamicDefender) fixA.getBody().getUserData();
                  defender.EnemyEnteredSpotRange(fixB.getBody());
                }
                break;
              case ENTITY_DEFENDER_FIRE_SENSOR:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {
                  DynamicDefender defender = (DynamicDefender) fixA.getBody().getUserData();
                  defender.EnemyEnteredFireRange(fixB.getBody());
                }
            }
          }

          @Override
          public void endContact(Contact contact) {
            Fixture fixA = contact.getFixtureA();
            Fixture fixB = contact.getFixtureB();
            switch (fixA.getFilterData().categoryBits) {
              case SENSOR_NAVIGATION:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {}

                break;
              case SENSOR_GOAL:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {}

                break;
              case ENTITY_ENEMY:
                DynamicMonster monster = (DynamicMonster) fixA.getBody().getUserData();
                if (fixB.getFilterData().categoryBits == SENSOR_NAVIGATION) {

                } else if (fixB.getFilterData().categoryBits == SENSOR_GOAL) {

                } else if (fixB.getFilterData().categoryBits == ENTITY_DEFENDER_SPOTTING_SENSOR) {
                  DynamicDefender defender = (DynamicDefender) fixB.getBody().getUserData();
                  defender.EnemyExitedSpotRange(fixA.getBody());
                } else if (fixB.getFilterData().categoryBits == ENTITY_DEFENDER_FIRE_SENSOR) {
                  DynamicDefender defender = (DynamicDefender) fixB.getBody().getUserData();
                  defender.EnemyExitedFireRange(fixA.getBody());
                }
                break;
              case ENTITY_DEFENDER_SPOTTING_SENSOR:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {
                  DynamicDefender defender = (DynamicDefender) fixA.getBody().getUserData();
                  defender.EnemyExitedSpotRange(fixB.getBody());
                }
              case ENTITY_DEFENDER_FIRE_SENSOR:
                if (fixB.getFilterData().categoryBits == ENTITY_ENEMY) {
                  DynamicDefender defender = (DynamicDefender) fixA.getBody().getUserData();
                  defender.EnemyExitedFireRange(fixB.getBody());
                }
                break;
            }
          }

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

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

    createCheckpointSensor(4.5f, 9.5f, new Vector2(4.5f, 1.5f));
    createCheckpointSensor(4.5f, 1.5f, new Vector2(11.5f, 1.5f));
    createCheckpointSensor(11.5f, 1.5f, new Vector2(11.5f, 9.5f));
    createFinishlineSensor(11.5f, 9.5f);
    createIllegalBuildArea();
  }
Exemple #11
0
  private void createPhysicsWorld() {
    // we instantiate a new World with a proper gravity vector
    // and tell it to sleep when possible.
    world = new World(new Vector2(0, -10), true);

    float[] vertices = {
      -0.07421887f,
      -0.16276085f,
      -0.12109375f,
      -0.22786504f,
      -0.157552f,
      -0.7122401f,
      0.04296875f,
      -0.7122401f,
      0.110677004f,
      -0.6419276f,
      0.13151026f,
      -0.49869835f,
      0.08984375f,
      -0.3190109f
    };

    PolygonShape shape = new PolygonShape();
    shape.set(vertices);

    // next we create a static ground platform. This platform
    // is not moveable and will not react to any influences from
    // outside. It will however influence other bodies. First we
    // create a PolygonShape that holds the form of the platform.
    // it will be 100 meters wide and 2 meters high, centered
    // around the origin
    PolygonShape groundPoly = new PolygonShape();
    groundPoly.setAsBox(50, 1);

    // next we create the body for the ground platform. It's
    // simply a static body.
    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.type = BodyType.StaticBody;
    groundBody = world.createBody(groundBodyDef);

    // finally we add a fixture to the body using the polygon
    // defined above. Note that we have to dispose PolygonShapes
    // and CircleShapes once they are no longer used. This is the
    // only time you have to care explicitely for memomry managment.
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = groundPoly;
    fixtureDef.filter.groupIndex = 0;
    groundBody.createFixture(fixtureDef);
    groundPoly.dispose();

    // We also create a simple ChainShape we put above our
    // ground polygon for extra funkyness.
    ChainShape chainShape = new ChainShape();
    chainShape.createLoop(
        new Vector2[] {
          new Vector2(-10, 10), new Vector2(-10, 5), new Vector2(10, 5), new Vector2(10, 11),
        });
    BodyDef chainBodyDef = new BodyDef();
    chainBodyDef.type = BodyType.StaticBody;
    Body chainBody = world.createBody(chainBodyDef);
    chainBody.createFixture(chainShape, 0);
    chainShape.dispose();

    createBoxes();

    // You can savely ignore the rest of this method :)
    world.setContactListener(
        new ContactListener() {
          @Override
          public void beginContact(Contact contact) {
            // System.out.println("begin contact");
          }

          @Override
          public void endContact(Contact contact) {
            // System.out.println("end contact");
          }

          @Override
          public void preSolve(Contact contact, Manifold oldManifold) {
            // Manifold.ManifoldType type = oldManifold.getType();
            // Vector2 localPoint = oldManifold.getLocalPoint();
            // Vector2 localNormal = oldManifold.getLocalNormal();
            // int pointCount = oldManifold.getPointCount();
            // ManifoldPoint[] points = oldManifold.getPoints();
            // System.out.println("pre solve, " + type +
            // ", point: " + localPoint +
            // ", local normal: " + localNormal +
            // ", #points: " + pointCount +
            // ", [" + points[0] + ", " + points[1] + "]");
          }

          @Override
          public void postSolve(Contact contact, ContactImpulse impulse) {
            // float[] ni = impulse.getNormalImpulses();
            // float[] ti = impulse.getTangentImpulses();
            // System.out.println("post solve, normal impulses: " + ni[0] + ", " + ni[1] + ",
            // tangent impulses: " + ti[0] + ", " + ti[1]);
          }
        });
  }