Ejemplo n.º 1
0
  /**
   * Calculate the physics in our world for the given object.
   *
   * @param obj The object to move
   * @param timeStep The time since last evaluation in nanoseconds
   */
  public void simulate(Dynamic obj, long timeStep) {
    /* Actions:
     * 1. apply drag
     * 2. add forces to object
     *     - gravity (unless resting on block)
     *     - arrow keys
     *
     * 3. apply forces to object. (done by the object)
     *
     * 4. a) move in x axis
     * 5. a) resolve collisions in x axis
     *
     * 4. b) move in y axis
     * 5. b) resolve collisions in y axis
     */
    double seconds = timeStep / (double) NS_PER_S;

    // 1. apply drag
    obj.applyDrag(seconds);

    // 2. add forces
    obj.addForce(new Vector2D(0, GRAVITY));
    obj.addForce(keyForce);

    // 3. apply forces
    obj.applyForces(seconds);

    // get velocity in preparation for step 4
    Vector2D vel = obj.getVel();
    hero.setImage(tp.get(Texture.hero));

    // 4. a)  move x
    obj.move((int) (vel.x * seconds), 0);

    // 5. a) resolve collisions in x
    Point bad = getWorldCollision(obj, Texture.brick);
    //        bad = null;
    if (bad != null) {
      int resolution = world.escapeX(obj, vel.x * seconds, bad);

      obj.move(resolution, 0);
      obj.getVel().setX(0);
    }

    // 4. b)  move y
    obj.move(0, (int) (vel.y * seconds));

    // 5. b) resolve collisions in y
    bad = getWorldCollision(obj, Texture.brick);
    //        bad = null;
    if (bad != null) {
      int resolution = world.escapeY(obj, vel.y * seconds, bad);
      if (vel.y < 0) {
        hero.setOnGround(true);
        hero.setImage(tp.get(Texture.heroGround));
      }
      obj.move(0, resolution);
      obj.getVel().setY(0);
    } else {
      hero.setOnGround(false);
    }
  }