示例#1
0
 /**
  * Calculate the bounds of the possible children of the given actor. If actor has no children,
  * then resultOrigin and resultSize are set to actor's bounds.
  */
 public static void calculateBounds(Actor actor, Vector2 resultOrigin, Vector2 resultSize) {
   resultOrigin.set(0, 0);
   resultSize.set(actor.getWidth(), actor.getHeight());
   if (actor instanceof Group && ((Group) actor).getChildren().size > 0) {
     calculateBounds(((Group) actor).getChildren(), resultOrigin, resultSize);
   }
 }
示例#2
0
 public boolean isPlaceEmpty(Vector2 pos, boolean considerPlanets) {
   Planet np = myPlanetManager.getNearestPlanet(pos);
   if (considerPlanets) {
     boolean inPlanet = np.getPos().dst(pos) < np.getFullHeight();
     if (inPlanet) return false;
   }
   SolSystem ns = myPlanetManager.getNearestSystem(pos);
   if (ns.getPos().dst(pos) < SunSingleton.SUN_HOT_RAD) return false;
   List<SolObject> objs = myObjectManager.getObjs();
   for (int i = 0, objsSize = objs.size(); i < objsSize; i++) {
     SolObject o = objs.get(i);
     if (!o.hasBody()) continue;
     if (pos.dst(o.getPos()) < myObjectManager.getRadius(o)) {
       return false;
     }
   }
   List<FarObjData> farObjs = myObjectManager.getFarObjs();
   for (int i = 0, farObjsSize = farObjs.size(); i < farObjsSize; i++) {
     FarObjData fod = farObjs.get(i);
     FarObj o = fod.fo;
     if (!o.hasBody()) continue;
     if (pos.dst(o.getPos()) < o.getRadius()) {
       return false;
     }
   }
   return true;
 }
  public static boolean inLineOfSight(Vector2 p1, Vector2 p2, Polygon polygon, boolean obstacle) {
    tmp.set(p1);
    tmp2.set(p2);

    float verts[] = polygon.getTransformedVertices();

    for (int i = 0; i < verts.length; i += 2) {
      if (lineSegmentsCross(
          tmp.x,
          tmp.y,
          tmp2.x,
          tmp2.y,
          verts[i],
          verts[i + 1],
          verts[(i + 2) % verts.length],
          verts[(i + 3) % verts.length])) return false;
    }

    tmp.add(tmp2);
    tmp.x /= 2;
    tmp.y /= 2;

    boolean result = PolygonUtils.isPointInside(polygon, tmp.x, tmp.y, !obstacle);

    return obstacle ? !result : result;
  }
示例#4
0
  private void updateVertices() {
    verticesMustBeUpdated = false;

    Array<Vector2> vertices = new Array<Vector2>();

    float step = MathUtils.PI2 / (float) vertexCount;

    for (float i = 0; i < vertexCount; i++) {
      Vector2 v = new Vector2(radius, 0);
      v.rotateRad(step * i);
      vertices.add(v);
    }

    for (OutlinePolygon outlinePolygon : basic.outlinePolygons) {
      outlinePolygon.setVertices(vertices);
    }

    if (basic.texturePolygon != null) {
      basic.texturePolygon.setVertices(vertices);
    }

    if (basic.physicsThing != null) {
      ((Circle) basic.physicsThing).setRadius(radius);
    }
  }
 @Override
 public Vector2 accelerate(Vector2 acceleration, Animal animal) {
   // calculate the horizontal and vertical acceleration via Accelerometer
   acceleration.x = Gdx.input.getAccelerometerY();
   acceleration.y = -Gdx.input.getAccelerometerX();
   return acceleration;
 }
示例#6
0
 public void drawLine(
     TextureRegion tex, Vector2 p1, Vector2 p2, Color col, float width, boolean precise) {
   Vector2 v = SolMath.getVec(p2);
   v.sub(p1);
   drawLine(tex, p1.x, p1.y, SolMath.angle(v, precise), v.len(), col, width);
   SolMath.free(v);
 }
示例#7
0
  @Override
  protected void drawOnContainer(Graphics g) {
    // draw target arrows immediately above stack for active item only
    if (activeItem != null) {
      Vector2 arrowOrigin =
          new Vector2(
              activeItem.getLeft()
                  + VStack.CARD_WIDTH * FCardPanel.TARGET_ORIGIN_FACTOR_X
                  + VStack.PADDING
                  + VStack.BORDER_THICKNESS,
              activeItem.getTop()
                  + VStack.CARD_HEIGHT * FCardPanel.TARGET_ORIGIN_FACTOR_Y
                  + VStack.PADDING
                  + VStack.BORDER_THICKNESS);

      PlayerView activator = activeStackInstance.getActivatingPlayer();
      arrowOrigin = arrowOrigin.add(screenPos.x, screenPos.y);

      StackItemView instance = activeStackInstance;
      while (instance != null) {
        for (CardView c : instance.getTargetCards()) {
          TargetingOverlay.drawArrow(g, arrowOrigin, c, activator.isOpponentOf(c.getController()));
        }
        for (PlayerView p : instance.getTargetPlayers()) {
          TargetingOverlay.drawArrow(g, arrowOrigin, p, activator.isOpponentOf(p));
        }
        instance = instance.getSubInstance();
      }
    }
  }
示例#8
0
文件: Actor.java 项目: newisso/libgdx
 /**
  * Transforms the specified point in the actor's coordinates to be in the parent's coordinates.
  * Note this method will ONLY work for screen aligned, unrotated, unscaled actors!
  */
 public Vector2 localToParentCoordinates(Vector2 localCoords) {
   if (getRotation() != 0 || getScaleX() != 1 || getScaleY() != 1)
     throw new GdxRuntimeException("Only unrotated and unscaled actors may use this method.");
   localCoords.x += getX();
   localCoords.y += getY();
   return localCoords;
 }
  /////////////////// SERVER
  @Override
  public void onReceivedNewPacket(Packet pack, Entity ent) {
    PhysixBodyComponent phxc = ComponentMappers.physixBody.get(ent);
    try {

      MovementPacket p = (MovementPacket) pack;
      InventoryComponent inventory = ComponentMappers.inventory.get(ent);
      MoveComponent move = ComponentMappers.move.get(ent);

      Vector2 vel = dummyVector.set(p.xPos, p.yPos);

      if ((inventory.getMetalShards() <= inventory.maxMetalShards)
          && (inventory.getMetalShards() > 0)) {
        float invtemp = (float) inventory.getMetalShards() / (float) inventory.maxMetalShards;
        vel.scl(move.speed - move.speed * (invtemp * 0.75f));
      } else {
        vel.scl(move.speed);
      }

      phxc.setLinearVelocity(vel);
      // phxc.setAngle(p.rotation);
      phxc.setAngle(p.rotation * MathUtils.degreesToRadians);
    } catch (ClassCastException e) {
    }
  }
示例#10
0
  private void restart() {
    for (int i = 0; i < MAX_BALL_COUNT; i++) {
      float tx = rand.nextFloat() * 1.0f - 0.5f;
      float ty = WORLD_SIZE.y / 2 + BALL_SIZE.y * 5;
      float angle = rand.nextFloat() * MathUtils.PI * 2;

      ballModels[i].setActive(false);
      ballModels[i].setLinearVelocity(tmpVec.set(0, 0));
      ballModels[i].setAngularVelocity(0);
      ballModels[i].setTransform(tmpVec.set(tx, ty), angle);
    }

    if (timer != null) timer.cancel();

    timerBallIndex = 0;
    timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          @Override
          public void run() {
            if (timerBallIndex < ballModels.length) {
              ballModels[timerBallIndex].setAwake(true);
              ballModels[timerBallIndex].setActive(true);
              timerBallIndex += 1;
            } else {
              timer.cancel();
            }
          }
        },
        100,
        100);
  }
示例#11
0
文件: Bird.java 项目: sduc/zombiebird
  public void update(float delta) {

    velocity.add(acceleration.cpy().scl(delta));

    if (velocity.y > 200) {
      velocity.y = 200;
    }

    position.add(velocity.cpy().scl(delta));

    boundingCircle.set(position.x + 9, position.y + 6, 6.5f);

    if (velocity.y < 0) {
      rotation -= 600 * delta;

      if (rotation < -20) {
        rotation = -20;
      }
    }

    if (isFalling()) {
      rotation += 480 * delta;
      if (rotation > 90) {
        rotation = 90;
      }
    }
  }
 @Override
 protected void processEntity(Entity entity, float deltaTime) {
   PlatformMonsterComp pm = entity.getComponent(PlatformMonsterComp.class);
   MonsterMovementComp mm = entity.getComponent(MonsterMovementComp.class);
   BodyComp b = entity.getComponent(BodyComp.class);
   Vector2 pos = b.body.getPosition();
   pos.x *= b.invWorldScale;
   pos.y *= b.invWorldScale;
   switch (mm.moveType) {
     case LEFT:
       if (pos.x <= pm.minX) {
         standMonster(pm, mm);
       }
       break;
     case STAND:
       if (pm.standCountdown > 0) {
         pm.standCountdown -= deltaTime;
       }
       if (pm.standCountdown <= 0) {
         pm.standCountdown = 0;
         if (pos.x <= pm.minX) {
           mm.moveType = MonsterMovementComp.MoveType.RIGHT;
         } else {
           mm.moveType = MonsterMovementComp.MoveType.LEFT;
         }
       }
       break;
     case RIGHT:
       if (pos.x >= pm.maxX) {
         standMonster(pm, mm);
       }
       break;
   }
 }
示例#13
0
  @Override
  public boolean touchDragged(int screenX, int screenY, int pointer) {

    if (currently_pressed_object != null) {
      //	System.out.println ("touch draggeding object!");

      Vector2 modified_values = (get_screen_to_stage_coordinates(screenX, screenY));

      ////
      // compensate for movie_display_group_offset

      modified_values.sub(view.MOVIE_DISPLAY_GROUP_OFFSET);

      ////
      // compensate for click position offset, otherwise the dragging will always occur with the
      // cursor at the lower left of the oject

      if (click_offset != null) modified_values.sub(click_offset);

      currently_pressed_object.set_position(modified_values);
      currently_pressed_object.update_properties();

      //				editor.get_properties_editor ().update_rows ();
      editor.get_properties_editor().update_rows_data();

      editor.get_display_info_panel().update_currently_pressed_object(currently_pressed_object);
    }
    return false;
  }
示例#14
0
  public static float getAngle(Vector2 v1, Vector2 v2) {
    Vector2 temp = v2.cpy();

    temp.sub(v1);

    return (float) Math.atan2(temp.y, temp.x);
  }
示例#15
0
  public void drawLineShapePart(
      Vector2 center,
      int verts,
      float innerPos,
      float outerPos,
      float rotation,
      Color innerCol,
      Color outerCol) {
    setType(GL20.GL_TRIANGLE_STRIP);

    n_verts = (verts + 1) * 2 + 2;
    checkMaxVerts(n_verts);

    a.set(CircleLogic.findPos(center, innerPos, 0 * (360f / verts) + rotation, 0f));

    // We place the vertex twice at the start and at the end to ensure no crosover from the last
    // shape
    putVertex(a.x, a.y, innerCol);
    putVertex(a.x, a.y, innerCol);
    for (int i = 0; i < verts + 1; i++) {
      a.set(CircleLogic.findPos(center, outerPos, i * (360f / verts) + rotation, 0f));
      putVertex(a.x, a.y, outerCol);
      a.set(CircleLogic.findPos(center, innerPos, i * (360f / verts) + rotation, 0f));
      putVertex(a.x, a.y, innerCol);
    }
    putVertex(a.x, a.y, innerCol);
  }
示例#16
0
 @Override
 public void reset() {
   moveDirection.setZero();
   lastMoveDirection.setZero();
   dropItem = false;
   speed = 0;
 }
  @Override
  public boolean mouseMoved(InputEvent event, float x, float y) {
    Vector2 scrolling = new Vector2();
    float zone = 10;
    float halfWidth = getStage().getViewport().getWorldWidth() * 0.5f;
    float halfHeight = getStage().getViewport().getWorldHeight() * 0.5f;
    Vector3 cameraPosition = getStage().getCamera().position;
    float west = cameraPosition.x - halfWidth + zone;
    float east = cameraPosition.x + halfWidth - zone;
    float north = cameraPosition.y + halfHeight - zone;
    float south = cameraPosition.y - halfHeight + zone;

    if (x <= west) {
      scrolling.x = -1;
    }
    if (x >= east) {
      scrolling.x = 1;
    }

    if (y >= north) {
      scrolling.y = 1;
    }
    if (y <= south) {
      scrolling.y = -1;
    }

    Service.eventQueue().enqueue(new Event(EventName.MOVING_CAMERA, scrolling));
    return super.mouseMoved(event, x, y);
  }
示例#18
0
  /**
   * Calculates the culling area of the bounding box after it has scaled, rotated and translates.
   * This bounding box contains a bunch of vertices. This way i don't have to merge hundreds of
   * vertices to get a reasonable culling area, just the four of the bounding box.
   */
  private Rectangle getCullingArea(
      Rectangle cullingArea,
      Rectangle boundingBox,
      float rotation,
      Vector2 translation,
      float scale) {

    tmp.set(boundingBox.x, boundingBox.y).scl(scale).rotateRad(rotation).add(translation);
    cullingArea.set(tmp.x, tmp.y, 0, 0);

    tmp.set(boundingBox.x + boundingBox.width, boundingBox.y)
        .scl(scale)
        .rotateRad(rotation)
        .add(translation);
    cullingArea.merge(tmp);

    tmp.set(boundingBox.x + boundingBox.width, boundingBox.y + boundingBox.height)
        .scl(scale)
        .rotateRad(rotation)
        .add(translation);
    cullingArea.merge(tmp);

    tmp.set(boundingBox.x, boundingBox.y + boundingBox.height)
        .scl(scale)
        .rotateRad(rotation)
        .add(translation);
    cullingArea.merge(tmp);

    return cullingArea;
  }
示例#19
0
 public void update(float delta) {
   position.add(velocity.cpy().scl(delta));
   // If the Scrollable object is no longer visible
   if (position.x + width < 0) {
     isScrolledLeft = true;
   }
 }
示例#20
0
  private void drawCullingRectangles(ShapeRenderer shapeRenderer, Color color) {
    for (BoundingBox br : boundingBoxes) {

      Rectangle r = br.rectangle;
      Rectangle cullingArea = getCullingArea(tmpRectangle, r, angleRad, position, scale);

      shapeRenderer.set(ShapeRenderer.ShapeType.Filled);

      Color fillColor = tmpColor.set(color);
      fillColor.a *= 0.25f;

      shapeRenderer.setColor(fillColor);

      shapeRenderer.rect(cullingArea.x, cullingArea.y, cullingArea.width, cullingArea.height);

      tmp.set(r.x, r.y).rotateRad(angleRad).add(position);
      tmp1.set(r.x + r.width, r.y).rotateRad(angleRad).add(position);
      tmp2.set(r.x + r.width, r.y + r.height).rotateRad(angleRad).add(position);
      tmp3.set(r.x, r.y + r.height).rotateRad(angleRad).add(position);

      shapeRenderer.set(ShapeRenderer.ShapeType.Line);
      shapeRenderer.setColor(color);

      shapeRenderer.line(tmp, tmp1);
      shapeRenderer.line(tmp1, tmp2);
      shapeRenderer.line(tmp2, tmp3);
      shapeRenderer.line(tmp3, tmp);
    }
  }
  private void walkToNextStep(CharacterActor target) {
    Vector2 p0 = walkingPath.get(currentStep);
    Vector2 pf = walkingPath.get(currentStep + 1);

    target.startWalkAnim(p0, pf);

    float s0 = target.getScene().getFakeDepthScale(p0.y);
    float sf = target.getScene().getFakeDepthScale(pf.y);

    //		float segmentDuration = p0.dst(pf)
    //				/ (EngineAssetManager.getInstance().getScale() * speed);

    // t = dst/((vf+v0)/2)
    float segmentDuration =
        p0.dst(pf) / (EngineAssetManager.getInstance().getScale() * speed * (s0 + sf) / 2);

    segmentDuration *= (s0 > sf ? s0 / sf : sf / s0);

    Interpolation i = Interpolation.linear;

    if (Math.abs(s0 - sf) > .25) i = s0 > sf ? Interpolation.pow2Out : Interpolation.pow2In;

    if (currentStep == walkingPath.size() - 2 && walkCb != null) {
      start(
          target, Type.NO_REPEAT, 1, pf.x, pf.y, segmentDuration, Interpolation.linear, i, walkCb);
    } else {
      start(target, Type.NO_REPEAT, 1, pf.x, pf.y, segmentDuration, Interpolation.linear, i, null);
    }
  }
示例#22
0
  private void tryMove() {
    bounds.x += vel.x;
    fetchCollidableRects();
    for (int i = 0; i < r.length; i++) {
      Rectangle rect = r[i];
      if (bounds.overlaps(rect)) {
        if (vel.x < 0) bounds.x = rect.x + rect.width + 0.01f;
        else bounds.x = rect.x - bounds.width - 0.01f;
        vel.x = 0;
      }
    }

    bounds.y += vel.y;
    fetchCollidableRects();
    for (int i = 0; i < r.length; i++) {
      Rectangle rect = r[i];
      if (bounds.overlaps(rect)) {
        if (vel.y < 0) {
          bounds.y = rect.y + rect.height + 0.01f;
        } else bounds.y = rect.y - bounds.height - 0.01f;
        vel.y = 0;
      }
    }

    pos.x = bounds.x - 0.2f;
    pos.y = bounds.y - 0.2f;
  }
 public static boolean hasArrived(Entity entity) {
   EnemyMovement enemyMovement = EntityUtil.getComponent(entity, EnemyMovement.class);
   Vector2 intent = enemyMovement.getIntent().cpy();
   Vector2 position = PhysicsUtil.getPosition(entity);
   intent.y = position.y;
   return position.epsilonEquals(intent, Constants.GAME.EPSILON);
 }
  /**
   * Clamp the point to the nearest polygon segment
   *
   * @param poly The polygon
   * @param x The original point X
   * @param y The original point Y
   * @param dest The clamped point
   * @return The segment where the clamped point belongs
   */
  public static int getClampedPoint(Polygon poly, float x, float y, Vector2 dest) {
    float verts[] = poly.getTransformedVertices();
    float dTmp;

    Intersector.nearestSegmentPoint(verts[0], verts[1], verts[2], verts[3], x, y, dest);

    int nearest = 0;
    float d = Vector2.dst(x, y, dest.x, dest.y);

    for (int i = 2; i < verts.length; i += 2) {
      Intersector.nearestSegmentPoint(
          verts[i],
          verts[i + 1],
          verts[(i + 2) % verts.length],
          verts[(i + 3) % verts.length],
          x,
          y,
          tmp);
      dTmp = Vector2.dst(x, y, tmp.x, tmp.y);

      if (dTmp < d) {
        d = dTmp;
        nearest = i;
        dest.set(tmp);
      }
    }

    return nearest;
  }
示例#25
0
 @Override
 public boolean onEnd(
     final Draggable draggable, final Actor actor, final float stageX, final float stageY) {
   if (actor == null || actor.getStage() == null) {
     return CANCEL;
   }
   final Actor overActor = actor.getStage().hit(stageX, stageY, true);
   if (overActor == null || overActor == actor) {
     return CANCEL;
   } else if (overActor.isAscendantOf(actor)) {
     final DragPane dragPane = getDragPane(actor);
     if (dragPane != null && dragPane.isFloating()) {
       DRAG_POSITION.set(stageX, stageY);
       return addToFloatingGroup(draggable, actor, dragPane);
     }
     return CANCEL;
   }
   DRAG_POSITION.set(stageX, stageY);
   if (overActor instanceof DragPane) {
     return addDirectlyToPane(draggable, actor, (DragPane) overActor);
   }
   final DragPane dragPane = getDragPane(overActor);
   if (accept(actor, dragPane)) {
     return addActor(draggable, actor, overActor, dragPane);
   }
   return CANCEL;
 }
示例#26
0
 public void lvlChanged(int bouclier) {
   positionEmiter.nor();
   positionEmiter.scl(originalScale);
   positionEmiter.scl(1 + (bouclier * 0.6f));
   speed = 40;
   speed += (bouclier * 0.66f) * speed;
 }
示例#27
0
  public void movePlayer(Touchpad touchpad) {
    float touchX = touchpad.getKnobPercentX();
    float touchY = touchpad.getKnobPercentY();

    if (touchX < -0.1 && touchX < -Math.abs(touchY)) {
      spriteVector.y = 0;
      spriteVector.x = -SPRITE_SPEED;
      spriteDirection = SpriteDirection.e;
    } else if (touchX > 0.1 && touchX > Math.abs(touchY)) {
      spriteVector.y = 0;
      spriteVector.x = SPRITE_SPEED;
      spriteDirection = SpriteDirection.w;
    } else if (touchY < -0.1 && touchY <= -Math.abs(touchX)) {
      spriteVector.x = 0;
      spriteVector.y = -SPRITE_SPEED;
      spriteDirection = SpriteDirection.s;
    } else if (touchY > 0.1 && touchY >= Math.abs(touchX)) {
      spriteVector.x = 0;
      spriteVector.y = SPRITE_SPEED;
      spriteDirection = SpriteDirection.n;
    } else if (touchX <= 0.1 && touchX >= -0.1 && touchY <= 0.1 && touchY >= -0.1) {
      spriteVector.x = 0;
      spriteVector.y = 0;
    }

    if (spriteVector.x == 0 && spriteVector.y == 0) spriteState = State.Idle;
    else spriteState = State.Walking;
  }
示例#28
0
文件: Player.java 项目: marshauf/uni
 @Override
 public void read(Json json, JsonValue jsonData) {
   Iterator<JsonValue> iter = jsonData.iterator();
   JsonValue value;
   while (iter.hasNext()) {
     value = iter.next();
     switch (value.name()) {
       case "name":
         name = value.asString();
         break;
       case "dir":
         dir.x = value.get("x").asFloat();
         dir.y = value.get("x").asFloat();
         break;
       case "speed":
         speed = value.asFloat();
         break;
       case "bounds":
         bounds.width = value.getFloat("width");
         bounds.height = value.getFloat("height");
         setPosition(
             new Vector2(
                 value.getFloat("x") + bounds.width / 2, value.getFloat("y") + bounds.height / 2));
         break;
       case "score":
         score.read(json, value);
         break;
     }
   }
 }
示例#29
0
 private TextField findNextTextField(
     Array<Actor> actors, TextField best, Vector2 bestCoords, Vector2 currentCoords, boolean up) {
   for (int i = 0, n = actors.size; i < n; i++) {
     Actor actor = actors.get(i);
     if (actor == this) continue;
     if (actor instanceof TextField) {
       TextField textField = (TextField) actor;
       if (textField.isDisabled() || !textField.focusTraversal) continue;
       Vector2 actorCoords =
           actor.getParent().localToStageCoordinates(tmp3.set(actor.getX(), actor.getY()));
       if ((actorCoords.y < currentCoords.y
               || (actorCoords.y == currentCoords.y && actorCoords.x > currentCoords.x))
           ^ up) {
         if (best == null
             || (actorCoords.y > bestCoords.y
                     || (actorCoords.y == bestCoords.y && actorCoords.x < bestCoords.x))
                 ^ up) {
           best = (TextField) actor;
           bestCoords.set(actorCoords);
         }
       }
     } else if (actor instanceof Group)
       best =
           findNextTextField(((Group) actor).getChildren(), best, bestCoords, currentCoords, up);
   }
   return best;
 }
示例#30
0
文件: Entity.java 项目: dset/Tetra
 /** Returns the distance between this entity and the given entity in pixels. */
 public float getDistancePixels(Entity other) {
   Vector2 thisPos = getCenter();
   Vector2 otherPos = other.getCenter();
   float distance = thisPos.dst(otherPos);
   Vector2Pool.recycle(thisPos);
   Vector2Pool.recycle(otherPos);
   return distance;
 }