public void addAreaObject(String worldname, String objname, LayoutArea area, ObjectProps props) {
    Box2dData data = this.mBox2dWorlds.get(worldname);
    if (data == null) {
      return;
    }

    // Dynamic Body
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DYNAMIC;
    bodyDef.position.set(area.mLocation[0], area.mLocation[1]);
    Body body = data.mWorld.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.setAsBox(area.mBounds[0] / 2, area.mBounds[1] / 2);
    fixtureDef.shape = dynamicBox;

    fixtureDef.density = props.mDensity;
    fixtureDef.friction = props.mFriction;
    fixtureDef.restitution = props.mRestitution;
    // kinematicBody
    fixtureDef.filter.groupIndex = props.mGroupIndex;
    body.createFixture(fixtureDef);

    BodyData bodydata = new BodyData();
    bodydata.mArea = area;
    bodydata.mBody = body;
    bodydata.mProps = props;
    area.assignPsyData(bodydata);
    data.mAreaModels.add(bodydata);
  }
Example #2
0
  private Body initPhysicsBody(World world, float x, float y) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DYNAMIC;
    bodyDef.position = new Vec2(0, 0);
    Body body = world.createBody(bodyDef);

    PolygonShape shape = new PolygonShape();
    Transform fx = new Transform();
    fx.position.set(100f, 100f);
    shape.centroid(fx);

    shape.setAsBox(
        sprite.layer().width() * GameScreen.M_PER_PIXEL / 2,
        sprite.layer().height() * GameScreen.M_PER_PIXEL / 2);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 0.4f;
    fixtureDef.friction = 0.1f;
    fixtureDef.restitution = 0f;
    body.createFixture(fixtureDef);
    body.setLinearDamping(0.2f);
    body.setTransform(new Vec2(x, y), 0f);

    //        MassData md = body.getMassData();
    //        massD.center.set(2f, 0); body.setMassData(massD);

    return body;
  }
Example #3
0
  /** 创建多边形物体 */
  private void createBody() {
    // 定义物体的形状是多边形形状
    PolygonShape shape = new PolygonShape();
    shape.set(vecs, edge);

    // 设置多边形物体的一些固定的物理属性
    FixtureDef fd = new FixtureDef();
    fd.shape = shape;
    // 固定设置参数
    fd.density = 5.0f; // 密度
    fd.friction = 0.3f; // 摩擦系数
    fd.restitution = restitution; // 恢复系数

    BodyDef bd = new BodyDef();
    bd.position.set(x, y);
    bd.type = BodyType.DYNAMIC;
    bd.angle = angle;
    bd.allowSleep = true;
    bd.setAwake(true);

    // 根据bodyDef创建物体到世界中
    body = world.createBody(bd);
    // 设置好物体的固定属性
    body.createFixture(fd);
  }
Example #4
0
  /** Inits the Box2D shape with default or passed values. */
  private void init() {
    mFixtureDef = new FixtureDef();
    // default values
    mFixtureDef.density = 10;
    mFixtureDef.friction = 0.3f;
    mFixtureDef.restitution = 0.5f;

    switch (mType) {
      case CIRCLE:
        mShape = new CircleShape();
        break;
      default:
        mShape = new PolygonShape();
    }
  }
Example #5
0
  @Override
  Body initPhysicsBody(World world, float x, float y, float width, float height, float angle) {
    FixtureDef fixtureDef = new FixtureDef();
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DYNAMIC;
    bodyDef.position = new Vec2(0, 0);
    Body body = world.createBody(bodyDef);

    CircleShape circleShape = new CircleShape();
    circleShape.m_radius = RADIUS;
    fixtureDef.shape = circleShape;
    fixtureDef.density = 0.4f;
    fixtureDef.friction = 1f;
    fixtureDef.restitution = 0.0f;
    circleShape.m_p.set(0, 0);
    body.createFixture(fixtureDef);
    //        body.setLinearDamping(0.2f);
    body.setTransform(new Vec2(x, y), angle);
    return body;
  }
  public void addDynObject(
      String worldname, String objname, GameonModelRef ref, ObjectProps props) {
    Box2dData data = this.mBox2dWorlds.get(worldname);
    if (data == null) {
      return;
    }

    // Dynamic Body
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DYNAMIC;
    bodyDef.position.set(ref.mPosition[0], ref.mPosition[1]);
    Body body = data.mWorld.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    if (props.mShape == SHAPE_BOX) {
      PolygonShape dynamicBox = new PolygonShape();
      dynamicBox.setAsBox(ref.mScale[0] / 2, ref.mScale[1] / 2);
      fixtureDef.shape = dynamicBox;
    } else {
      CircleShape dynamicCircle = new CircleShape();
      dynamicCircle.m_radius = ref.mScale[0] / 2;
      fixtureDef.shape = dynamicCircle;
    }

    fixtureDef.density = props.mDensity;
    fixtureDef.friction = props.mFriction;
    fixtureDef.restitution = props.mRestitution;
    // kinematicBody
    fixtureDef.filter.groupIndex = props.mGroupIndex;
    body.createFixture(fixtureDef);

    BodyData bodydata = new BodyData();
    bodydata.mRef = ref;
    bodydata.mBody = body;
    bodydata.mProps = props;
    ref.assignPsyData(bodydata);
    data.mDynModels.add(bodydata);
  }
  public PhysicsObject(float x, float y, int w, int h, BodyType t) {
    pos.x = x;
    pos.y = y;
    height = h;
    width = w;

    shape = new PolygonShape();
    shape.setAsBox(
        (width / 2) / PhysicsInvaders.PTM_RATIO, (height / 2) / PhysicsInvaders.PTM_RATIO);

    FixtureDef fd = new FixtureDef();
    fd.shape = shape;
    fd.density = 100;
    fd.friction = 0.9f;
    fd.restitution = 0.1f;

    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(pos.x / PhysicsInvaders.PTM_RATIO, pos.y / PhysicsInvaders.PTM_RATIO);
    bodyDef.type = t;

    body = PhysicsInvaders.world.createBody(bodyDef);
    body.createFixture(fd);
  }
Example #8
0
  /**
   * Instead of using a square shape, we will use a round one.
   *
   * @param body the body created before.
   */
  @Override
  public void createFixturesForBody(Body body) {
    // Use vertices to create fixture shape.
    CircleShape shape = new CircleShape();

    shape.setRadius(getWidth() * GameRenderer.getMPP());

    // Attach fixture
    FixtureDef fd = new FixtureDef();
    fd.shape = shape;
    fd.density = getDensity();
    fd.friction = getFriction();
    fd.restitution = getRestitution();

    // Continue the fixture definition.
    configureFixtureDefinition(fd);

    // We set to the fixture's user data this model, so we can get it later
    // when getting collisions.
    body.createFixture(fd).setUserData(this);

    body.applyForceToCenter(new Vec2(0f, 4f));
  }
Example #9
0
  /**
   * Create a new paddle.
   *
   * @param world The world the paddle will be added to.
   * @param y The height of the paddle (starts centered on the x)
   * @param mode The keys that will move this paddle
   */
  public Paddle(World world, int y, MovementMode mode) {
    Mode = mode;

    // Respond to the keyboard
    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventDispatcher(this);

    // Add the physics body
    BodyDef bd = new BodyDef();
    bd.type = BodyType.DYNAMIC;
    bd.position.set(world.Bounds.width / 2, y);
    bd.linearDamping = 0.0f;
    bd.angularDamping = 0.01f;

    FixtureDef fd = new FixtureDef();
    fd.shape = new PolygonShape();
    ((PolygonShape) fd.shape).setAsBox(SIZE.width / 2, SIZE.height / 2);
    fd.density = 0.1f;
    fd.friction = 0.0f;
    fd.restitution = 1.0f;

    j2dBody = world.j2dWorld.createBody(bd);
    j2dBody.createFixture(fd);
    j2dBody.setUserData(this);

    // Limit it to only x movement
    BodyDef gbd = new BodyDef();
    gbd.type = BodyType.STATIC;
    bd.position.set(world.Bounds.width / 2, y);

    PrismaticJointDef pjd = new PrismaticJointDef();
    pjd.collideConnected = true;
    pjd.initialize(
        j2dBody, world.j2dWorld.createBody(gbd), j2dBody.getWorldCenter(), new Vec2(1.0f, 0.0f));
    world.j2dWorld.createJoint(pjd);
  }
Example #10
0
  // Constructor
  Box(PApplet parent, PBox2D box2d, float x, float y, float w_, float h_, boolean lock) {

    this.parent = parent;
    this.box2d = box2d;

    w = w_;
    h = h_;

    // Define and create the body
    BodyDef bd = new BodyDef();
    bd.position.set(box2d.coordPixelsToWorld(new Vec2(x, y)));
    if (lock) bd.type = BodyType.STATIC;
    else bd.type = BodyType.DYNAMIC;

    body = box2d.createBody(bd);

    // Define the shape -- a  (this is what we use for a rectangle)
    PolygonShape sd = new PolygonShape();
    float box2dW = box2d.scalarPixelsToWorld(w / 2);
    float box2dH = box2d.scalarPixelsToWorld(h / 2);
    sd.setAsBox(box2dW, box2dH);

    // Define a fixture
    FixtureDef fd = new FixtureDef();
    fd.shape = sd;
    // Parameters that affect physics
    fd.density = 1;
    fd.friction = 0.3f;
    fd.restitution = 0.5f;

    body.createFixture(fd);

    // Give it some initial random velocity
    body.setLinearVelocity(new Vec2(parent.random(-5, 5), parent.random(2, 5)));
    body.setAngularVelocity(parent.random(-5, 5));
  }
  /**
   * Rozbije objekt. Upravi objekt world tak, ze vymaze triesteny objekt a nahradi ho fragmentami na
   * zaklade nastaveneho materialu a clenskych premennych.
   *
   * @param dt casova dlzka framu
   */
  public void smash(float dt) {
    if (contact == null) { // riesi sa staticky prvok, ktory ma priliz maly obsah
      b1.setType(BodyType.DYNAMIC);
      return;
    }

    World w = b1.m_world;
    Shape s = f1.m_shape;
    Polygon p = f1.m_polygon;

    if (p == null) {
      switch (s.m_type) {
        case POLYGON:
          PolygonShape ps = (PolygonShape) s;
          Vec2[] vertices = ps.m_vertices;
          p = new Polygon();
          for (int i = 0; i < ps.m_count; ++i) {
            p.add(vertices[ps.m_count - i - 1]);
          }
          break;
        case CIRCLE:
          CircleShape cs = (CircleShape) s;
          p = new Polygon();
          float radius = cs.m_radius;

          double u = Math.PI * 2 / CIRCLEVERTICES;
          radius =
              (float) Math.sqrt(u / Math.sin(u))
                  * radius; // upravim radius tak, aby bola zachovana velkost obsahu

          Vec2 center = cs.m_p;
          for (int i = 0; i < CIRCLEVERTICES; ++i) {
            double j = u * i; // uhol
            float sin = (float) Math.sin(j);
            float cos = (float) Math.cos(j);
            Vec2 v = new Vec2(sin, cos).mulLocal(radius).addLocal(center);
            p.add(v);
          }
          break;
        default:
          throw new RuntimeException("Dany typ tvaru nepodporuje stiepenie");
      }
    }

    float mConst = f1.m_material.m_rigidity / normalImpulse; // sila v zavislosti na pevnosti telesa

    boolean fixA = f1 == contact.m_fixtureA; // true, ak f2 je v objekte contact ako m_fixtureA
    float oldAngularVelocity =
        fixA ? contact.m_angularVelocity_bodyA : contact.m_angularVelocity_bodyB;
    Vec2 oldLinearVelocity = fixA ? contact.m_linearVelocity_bodyA : contact.m_linearVelocity_bodyB;
    b1.setAngularVelocity(
        (b1.m_angularVelocity - oldAngularVelocity) * mConst + oldAngularVelocity);
    b1.setLinearVelocity(
        b1.m_linearVelocity.sub(oldLinearVelocity).mulLocal(mConst).addLocal(oldLinearVelocity));
    if (!w.isFractured(f2)
        && b2.m_type == BodyType.DYNAMIC
        && !b2.m_fractureTransformUpdate) { // ak sa druhy objekt nerozbija, tak sa jej nahodia
      // povodne hodnoty (TREBA MODIFIKOVAT POHYB OBJEKTU,
      // KTORY SPOSOBUJE ROZPAD)
      oldAngularVelocity =
          !fixA ? contact.m_angularVelocity_bodyA : contact.m_angularVelocity_bodyB;
      oldLinearVelocity = !fixA ? contact.m_linearVelocity_bodyA : contact.m_linearVelocity_bodyB;
      b2.setAngularVelocity(
          (b2.m_angularVelocity - oldAngularVelocity) * mConst + oldAngularVelocity);
      b2.setLinearVelocity(
          b2.m_linearVelocity.sub(oldLinearVelocity).mulLocal(mConst).addLocal(oldLinearVelocity));
      b2.setTransform(
          b2.m_xf0.p.add(b2.m_linearVelocity.mul(dt)),
          b2.m_xf0.q.getAngle()); // osetruje jbox2d od posuvania telesa pri rieseni kolizie
      b2.m_fractureTransformUpdate = true;
    }

    Vec2 localPoint = Transform.mulTrans(b1.m_xf, point);
    Vec2 b1Vec = b1.getLinearVelocityFromWorldPoint(point);
    Vec2 b2Vec = b2.getLinearVelocityFromWorldPoint(point);
    Vec2 localVector = b2Vec.subLocal(b1Vec);

    localVector.mulLocal(dt);
    Polygon[] fragment;
    try {
      fragment = m.split(p, localPoint, localVector, normalImpulse); // rodeli to
    } catch (RuntimeException ex) {
      return;
    }

    if (fragment.length == 1) { // nerozbilo to na ziadne fragmenty
      return;
    }

    // definuje tela fragmentov - tie maju vsetky rovnaku definiciu (preberaju parametre z povodneho
    // objektu)
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(b1.m_xf.p); // pozicia
    bodyDef.angle = b1.m_xf.q.getAngle(); // otocenie
    bodyDef.fixedRotation = b1.isFixedRotation();
    bodyDef.angularDamping = b1.m_angularDamping;
    bodyDef.allowSleep = b1.isSleepingAllowed();

    FixtureDef fd = new FixtureDef();
    fd.friction = f1.m_friction; // trenie
    fd.restitution = f1.m_restitution; // odrazivost
    fd.isSensor = f1.m_isSensor;
    fd.density = f1.m_density;

    // odstrani fragmentacne predmety/cele teleso
    ArrayList<Fixture> fixtures = new ArrayList<>();
    if (f1.m_polygon != null) {
      for (Fixture f = b1.m_fixtureList; f != null; f = f.m_next) {
        if (f.m_polygon == f1.m_polygon) {
          fixtures.add(f);
        }
      }
    } else {
      fixtures.add(f1);
    }

    for (Fixture f : fixtures) {
      b1.destroyFixture(f);
    }

    if (b1.m_fixtureCount == 0) {
      w.destroyBody(b1);
    }

    // prida fragmenty do simulacie
    MyList<Body> newbodies = new MyList<>();
    for (Polygon pg : fragment) { // vytvori tela, prida fixtury, poriesi konvexnu dekompoziciu
      if (pg.isCorrect()) {
        if (pg instanceof Fragment) {
          Polygon[] convex = pg.convexDecomposition();
          bodyDef.type = BodyType.DYNAMIC;
          for (Polygon pgx : convex) {
            Body f_body = w.createBody(bodyDef);
            pgx.flip();
            PolygonShape ps = new PolygonShape();
            ps.set(pgx.getArray(), pgx.size());
            fd.shape = ps;
            fd.polygon = null;
            fd.material = f1.m_material.m_fragments; // rekurzivne stiepenie

            f_body.createFixture(fd);
            f_body.setAngularVelocity(b1.m_angularVelocity);
            f_body.setLinearVelocity(b1.getLinearVelocityFromLocalPoint(f_body.getLocalCenter()));
            newbodies.add(f_body);
          }

        } else {
          fd.material = f1.m_material.m_fragments; // rekurzivne stiepenie
          bodyDef.type = b1.getType();
          Body f_body = w.createBody(bodyDef);
          PolygonFixture pf = new PolygonFixture(pg);

          f_body.createFixture(pf, fd);
          f_body.setLinearVelocity(b1.getLinearVelocityFromLocalPoint(f_body.getLocalCenter()));
          f_body.setAngularVelocity(b1.m_angularVelocity);
          newbodies.add(f_body);
        }
      }
    }

    // zavola sa funkcia z fraction listeneru (pokial je nadefinovany)
    FractureListener fl = w.getContactManager().m_fractureListener;
    if (fl != null) {
      fl.action(m, normalImpulse, newbodies);
    }
  }