// TODO: Refactor into multiple functions
  @Override
  public Entity buildEntity() {
    Entity player = new Entity();

    // Define the body
    BodyDef playerBody = new BodyDef();
    playerBody.type = BodyDef.BodyType.DynamicBody;
    playerBody.position.set(0, 0);

    // Create the components
    PhysicsComponent p = new PhysicsComponent(physicsWorld.createBody(playerBody), player);
    RenderComponent r = new RenderComponent();
    KeyboardInputComponent i = new KeyboardInputComponent();
    MoveAction m = new MoveAction();

    // Properties for the components
    Polygon sprite =
        new Polygon(
            new float[] {
              0, 5,
              3, -3,
              0, -2,
              -3, -3
            });

    PolygonShape fixShape = new PolygonShape();
    fixShape.set(sprite.getVertices());

    FixtureDef def = new FixtureDef();
    def.shape = fixShape;
    def.density = 1.2f;
    def.friction = 0f;
    def.restitution = 0.1f;

    // Apply properties
    p.physicsBody.createFixture(def);

    r.renderColor = Color.BLUE;
    r.sprite = sprite;

    m.lin_v = 5f;
    m.rot_v = 2f;

    // Add to player
    player.add(p);
    player.add(r);
    player.add(i);
    player.add(m);

    return player;
  }
Example #2
0
  public float[] getMeshVertices(Polygon poly) {
    // Top
    verticesMesh[0] = poly.getTransformedVertices()[0]; // go left X
    verticesMesh[1] = poly.getTransformedVertices()[1]; // go up Y

    // Right
    verticesMesh[4] = poly.getTransformedVertices()[2]; // go right X
    verticesMesh[5] = poly.getTransformedVertices()[3]; // go up Y

    // Bottom Right
    verticesMesh[8] = poly.getTransformedVertices()[4]; // go right X
    verticesMesh[9] = poly.getTransformedVertices()[5]; // go down Y

    return verticesMesh;
  }
  /**
   * 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;
  }
  public static void deletePoint(Polygon poly, int index) {

    float verts[] = poly.getVertices();

    if (verts.length < 8) return;

    int length = verts.length;
    float destination[] = new float[length - 2];

    //		index = index * 2;

    System.arraycopy(verts, 0, destination, 0, index);
    System.arraycopy(verts, index + 2, destination, index, length - index - 2);

    poly.setVertices(destination);
  }
  public static void addPoint(Polygon poly, float x, float y, int index) {
    float verts[] = poly.getVertices();

    x -= poly.getX();
    y -= poly.getY();

    int length = verts.length;
    float destination[] = new float[length + 2];

    System.arraycopy(verts, 0, destination, 0, index);
    destination[index] = x;
    destination[index + 1] = y;
    System.arraycopy(verts, index, destination, index + 2, length - index);

    poly.setVertices(destination);
  }
  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;
  }
 public TouchableEntity getTouchableEntity(AgentEntity agentEntity) {
   TouchableEntity touchableEntity = new TouchableEntity();
   DamageEffect damageEffect = new DamageEffect();
   damageEffect.setDamage(damage);
   damageEffect.setOriginatingAgent(agentEntity);
   touchableEntity.setCollisionPolygon(new Polygon(attackPolygon.getVertices()));
   Vector2 attackPosition = new Vector2();
   if (agentEntity.isFacingLeft()) {
     attackPosition
         .add(agentEntity.getLeftBoundingSide())
         .sub(attackPolygon.getBoundingRectangle().width, 0);
   } else {
     attackPosition.add(agentEntity.getRightBoundingSide());
   }
   touchableEntity.setPosition(attackPosition);
   return touchableEntity;
 }
  public static boolean deletePoint(Polygon poly, float x, float y, float tolerance) {
    float verts[] = poly.getTransformedVertices();

    for (int i = 0; i < verts.length; i += 2) {
      if (Vector2.dst(x, y, verts[i], verts[i + 1]) < tolerance) {
        deletePoint(poly, i);

        return true;
      }
    }

    return false;
  }
  public void drawBBoxLines(ShapeRenderer renderer) {
    // renderer.begin(ShapeType.Rectangle);
    renderer.begin(ShapeType.Line);

    for (BaseActor a : actors.values()) {
      Polygon p = a.getBBox();

      if (p == null) {
        EngineLogger.error("ERROR DRAWING BBOX FOR: " + a.getId());
      }

      if (a instanceof ObstacleActor) renderer.setColor(OBSTACLE_COLOR);
      else renderer.setColor(ACTOR_BBOX_COLOR);

      renderer.polygon(p.getTransformedVertices());

      // Rectangle r = a.getBBox().getBoundingRectangle();
      // renderer.rect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
    }

    if (polygonalNavGraph != null) {
      renderer.setColor(WALKZONE_COLOR);
      renderer.polygon(polygonalNavGraph.getWalkZone().getTransformedVertices());

      // DRAW LINEs OF SIGHT
      renderer.setColor(Color.WHITE);
      ArrayList<NavNodePolygonal> nodes = polygonalNavGraph.getGraphNodes();
      for (NavNodePolygonal n : nodes) {
        for (NavNode n2 : n.neighbors) {
          renderer.line(n.x, n.y, ((NavNodePolygonal) n2).x, ((NavNodePolygonal) n2).y);
        }
      }
    }

    renderer.end();
  }
  /**
   * Sets polygon with repeating texture region, the size of repeating grid is equal to region size
   *
   * @param region - region to repeat
   * @param vertices - cw vertices of polygon
   * @param density - number of regions per polygon width bound
   */
  public void setPolygon(TextureRegion region, float[] vertices, float density) {

    this.region = region;

    vertices = offset(vertices);

    Polygon polygon = new Polygon(vertices);
    Polygon tmpPoly = new Polygon();
    Polygon intersectionPoly = new Polygon();
    EarClippingTriangulator triangulator = new EarClippingTriangulator();

    int idx;

    Rectangle boundRect = polygon.getBoundingRectangle();

    if (density == -1) density = boundRect.getWidth() / region.getRegionWidth();

    float regionAspectRatio = (float) region.getRegionHeight() / (float) region.getRegionWidth();
    cols = (int) (Math.ceil(density));
    gridWidth = boundRect.getWidth() / density;
    gridHeight = regionAspectRatio * gridWidth;
    rows = (int) Math.ceil(boundRect.getHeight() / gridHeight);

    for (int col = 0; col < cols; col++) {
      for (int row = 0; row < rows; row++) {
        float[] verts = new float[8];
        idx = 0;
        verts[idx++] = col * gridWidth;
        verts[idx++] = row * gridHeight;
        verts[idx++] = (col) * gridWidth;
        verts[idx++] = (row + 1) * gridHeight;
        verts[idx++] = (col + 1) * gridWidth;
        verts[idx++] = (row + 1) * gridHeight;
        verts[idx++] = (col + 1) * gridWidth;
        verts[idx] = (row) * gridHeight;
        tmpPoly.setVertices(verts);

        Intersector.intersectPolygons(polygon, tmpPoly, intersectionPoly);
        verts = intersectionPoly.getVertices();
        if (verts.length > 0) {
          parts.add(snapToGrid(verts));
          ShortArray arr = triangulator.computeTriangles(verts);
          indices.add(arr.toArray());
        } else {
          // adding null for key consistancy, needed to get col/row from key
          // the other alternative is to make parts - IntMap<FloatArray>
          parts.add(null);
        }
      }
    }

    buildVertices();
  }
  public static boolean isPointInside(
      Polygon polygon, float x, float y, boolean toleranceOnOutside) {
    float verts[] = polygon.getTransformedVertices();

    boolean inside = false;

    float oldX = verts[verts.length - 2];
    float oldY = verts[verts.length - 1];

    float oldSqDist = Vector2.dst2(oldX, oldY, x, y);

    for (int i = 0; i < verts.length; i += 2) {
      float newX = verts[i];
      float newY = verts[i + 1];
      float newSqDist = Vector2.dst2(newX, newY, x, y);

      if (oldSqDist
              + newSqDist
              + 2.0f * Math.sqrt(oldSqDist * newSqDist)
              - Vector2.dst2(newX, newY, oldX, oldY)
          < TOLERANCE_IS_POINT_INSIDE) return toleranceOnOutside;

      float leftX = newX;
      float leftY = newY;
      float rightX = oldX;
      float rightY = oldY;

      if (newX > oldX) {
        leftX = oldX;
        leftY = oldY;
        rightX = newX;
        rightY = newY;
      }

      if (leftX < x
          && x <= rightX
          && (y - leftY) * (rightX - leftX) < (rightY - leftY) * (x - leftX)) inside = !inside;

      oldX = newX;
      oldY = newY;
      oldSqDist = newSqDist;
    }

    return inside;
  }
  public static boolean isVertexConcave(Polygon poly, int index) {
    float verts[] = poly.getTransformedVertices();

    float currentX = verts[index];
    float currentY = verts[index + 1];
    float nextX = verts[(index + 2) % verts.length];
    float nextY = verts[(index + 3) % verts.length];
    float previousX = verts[index == 0 ? verts.length - 2 : index - 2];
    float previousY = verts[index == 0 ? verts.length - 1 : index - 1];

    float leftX = currentX - previousX;
    float leftY = currentY - previousY;
    float rightX = nextX - currentX;
    float rightY = nextY - currentY;

    float cross = (leftX * rightY) - (leftY * rightX);

    return cross < 0;
  }
Example #13
0
  @Override
  public void start() {
    OwnedObjectData data = new OwnedObjectData();

    data.drawAfter = true;

    if (bullet.getTicksAlive() < 20) animationPlaying = true;

    createTick = game.getTick();

    bullet.addOwnedObject(this, data);

    final Sprite current = (Sprite) this.ani.getKeyFrame(getTicksAlive());

    Polygon hitbox = bullet.getHitbox();
    Rectangle rect =
        hitbox != null ? hitbox.getBoundingRectangle() : current.getBoundingRectangle();

    final float modifier = 3f;
    float width = rect.getWidth() * modifier;
    float height = rect.getHeight() * modifier;

    final float scaleX = width / current.getWidth();
    final float scaleY = height / current.getHeight();

    current.setScale(scaleX, scaleY);
    current.setRotation(bullet.getRotationDeg());

    current.setOriginCenter();

    Color c = bullet.getDeletionColor().cpy();

    float min = Math.min(c.g, Math.min(c.r, c.b));
    c.r -= min;
    c.g -= min;
    c.b -= min;

    float mul = 0.8f;
    float start = (1f - mul) + 0.3f;

    Color color = new Color(start + (c.r * mul), start + (c.g * mul), start + (c.b * mul), 0f);

    current.setColor(color);
    current.setAlpha(1f);

    final SaveableObject<ScaleAlphaPhaseAnimation> sani =
        new SaveableObject<ScaleAlphaPhaseAnimation>();

    Getter<Sprite> getter =
        new Getter<Sprite>() {
          @Override
          public Sprite get() {
            Sprite current = (Sprite) ani.getKeyFrame(getTicksAlive());

            int over = 5;

            int ticks = (int) ((time.toTicks() - over) - getTicksAlive());

            double mul = 1f - (ticks <= 0 ? -(float) ticks / over : 0f);

            ScaleAlphaPhaseAnimation ani = sani.getObject();

            if (ani == null) return current;

            if (ticks <= 0) {
              animationPlaying = false;
              ani.setAlpha((float) Math.max(0, mul));
            }

            current.setPosition(
                bullet.getX() - current.getWidth() / 2f, bullet.getY() - current.getHeight() / 2f);

            current.setOriginCenter();

            current.setRotation(bullet.getRotationDeg());

            return current;
          }
        };

    final ScaleAlphaPhaseAnimation ani = new ScaleAlphaPhaseAnimation(getter, bullet);

    sani.setObject(ani);

    ani.setTime(time);
    ani.setAddedScale(scaleX * 3f, scaleY * 3f);
    ani.setAlpha(-0.1f);
    ani.start();

    bullet.removeOwnedObject(ani);
    bullet.addOwnedObject(ani, data);
  }
Example #14
0
  protected void loadObject(MapLayer layer, Element element) {
    if (element.getName().equals("object")) {
      MapObject object = null;

      int x = element.getIntAttribute("x", 0);
      int y =
          (yUp
              ? mapHeightInPixels - element.getIntAttribute("y", 0)
              : element.getIntAttribute("y", 0));

      int width = element.getIntAttribute("width", 0);
      int height = element.getIntAttribute("height", 0);

      if (element.getChildCount() > 0) {
        Element child = null;
        if ((child = element.getChildByName("polygon")) != null) {
          String[] points = child.getAttribute("points").split(" ");
          float[] vertices = new float[points.length * 2];
          for (int i = 0; i < points.length; i++) {
            String[] point = points[i].split(",");
            vertices[i * 2] = Integer.parseInt(point[0]);
            vertices[i * 2 + 1] = Integer.parseInt(point[1]);
            if (yUp) {
              vertices[i * 2 + 1] *= -1;
            }
          }
          Polygon polygon = new Polygon(vertices);
          polygon.setPosition(x, y);
          object = new PolygonMapObject(polygon);
        } else if ((child = element.getChildByName("polyline")) != null) {
          String[] points = child.getAttribute("points").split(" ");
          float[] vertices = new float[points.length * 2];
          for (int i = 0; i < points.length; i++) {
            String[] point = points[i].split(",");
            vertices[i * 2] = Integer.parseInt(point[0]);
            vertices[i * 2 + 1] = Integer.parseInt(point[1]);
            if (yUp) {
              vertices[i * 2 + 1] *= -1;
            }
          }
          Polyline polyline = new Polyline(vertices);
          polyline.setPosition(x, y);
          object = new PolylineMapObject(polyline);
        } else if ((child = element.getChildByName("ellipse")) != null) {
          object = new EllipseMapObject(x, yUp ? y - height : y, width, height);
        }
      }
      if (object == null) {
        object = new RectangleMapObject(x, yUp ? y - height : y, width, height);
      }
      object.setName(element.getAttribute("name", null));
      String type = element.getAttribute("type", null);
      if (type != null) {
        object.getProperties().put("type", type);
      }
      int gid = element.getIntAttribute("gid", -1);
      if (gid != -1) {
        object.getProperties().put("gid", gid);
      }
      object.getProperties().put("x", x);
      object.getProperties().put("y", yUp ? y - height : y);
      object.setVisible(element.getIntAttribute("visible", 1) == 1);
      Element properties = element.getChildByName("properties");
      if (properties != null) {
        loadProperties(object.getProperties(), properties);
      }
      layer.getObjects().add(object);
    }
  }
 private void calculateVertices() {
   shape.setVertices(
       new float[] {
         x, y, x, y + hRatio * 110, x + 735 * hRatio, y + hRatio * 110, x + 625 * hRatio, y
       });
 }
 public boolean contains(float x, float y) {
   if (hidden || !click_enabled) return false;
   return shape.contains(x, y);
 }