Example usage for com.badlogic.gdx.math Vector2 set

List of usage examples for com.badlogic.gdx.math Vector2 set

Introduction

In this page you can find the example usage for com.badlogic.gdx.math Vector2 set.

Prototype

@Override
    public Vector2 set(Vector2 v) 

Source Link

Usage

From source file:com.agateau.pixelwheels.map.WaypointStore.java

License:Open Source License

public OrientedPoint getValidPosition(Vector2 pos, float lapDistance) {
    int nextIdx = getWaypointIndex(lapDistance);
    int prevIdx = getPreviousIndex(nextIdx);
    Vector2 prev = mWaypointInfos.get(prevIdx).waypoint;
    Vector2 next = mWaypointInfos.get(nextIdx).waypoint;
    Vector2 projected = AgcMathUtils.project(pos, prev, next);
    float waypointSquareLength = prev.dst2(next);
    if (projected.dst2(prev) > waypointSquareLength) {
        // projected is after the [prev, next] segment
        projected.set(next);
    } else if (projected.dst2(next) > waypointSquareLength) {
        // projected is before the [prev, next] segment
        projected.set(prev);//from   ww  w.  j a va2 s. com
    }
    tmpPoint.x = projected.x;
    tmpPoint.y = projected.y;
    tmpPoint.angle = AgcMathUtils.normalizeAngle(AgcMathUtils.segmentAngle(prev, next));
    return tmpPoint;
}

From source file:com.ahsgaming.valleyofbones.ai.AIPlayer.java

License:Apache License

@Override
public void update(GameController controller, float delta) {
    super.update(controller, delta);

    if (genome == null) {
        Json json = new Json();
        genome = json.fromJson(GenomicAI.class, Gdx.files.internal("ai/xjix3xuv").readString());
        Gdx.app.log(LOG, "Loaded ai: " + genome.id);
    }/*  w  w w  .j  a  v  a 2  s . c o m*/

    if (controller.getCurrentPlayer().getPlayerId() == getPlayerId()) {
        timer -= delta;
        if (timer < 0) {
            timer = countdown;

            if (VOBGame.DEBUG_AI)
                Gdx.app.log(LOG, "start...");
            // first, create the visibility matrix
            if (visibilityMatrix == null) {
                if (VOBGame.DEBUG_AI)
                    Gdx.app.log(LOG, "...create visibility matrix");
                visibilityMatrix = createVisibilityMatrix(controller.getMap(),
                        controller.getUnitsByPlayerId(getPlayerId()));
                return;
            }

            // next, create the value matrix and threat matrix
            if (valueMatrix == null) {
                Array<AbstractUnit> visibleUnits = new Array<AbstractUnit>();
                for (AbstractUnit unit : controller.getUnits()) {
                    if (visibilityMatrix[(int) (unit.getView().getBoardPosition().y
                            * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)]) {
                        visibleUnits.add(unit);
                    }
                }
                if (VOBGame.DEBUG_AI)
                    Gdx.app.log(LOG, "...create value/threat matrices");
                valueMatrix = createUnitMatrix(controller.getMap(), visibleUnits, false);
                threatMatrix = createUnitMatrix(controller.getMap(), visibleUnits, true);
                return;
            }

            // create goalMatrix (based on knowledge of the map)
            if (goalMatrix == null) {
                if (VOBGame.DEBUG_AI)
                    Gdx.app.log(LOG, "...create goal matrix");
                goalMatrix = createGoalMatrix(controller.getMap(), controller.getUnits());

                if (VOBGame.DEBUG_AI) {
                    DecimalFormat formatter = new DecimalFormat("00.0");
                    for (int y = 0; y < controller.getMap().getHeight(); y++) {
                        if (y % 2 == 1) {
                            System.out.print("   ");
                        }
                        for (int x = 0; x < controller.getMap().getWidth(); x++) {
                            int i = y * controller.getMap().getWidth() + x;
                            float sum = (visibilityMatrix[i] ? goalMatrix[i] + valueMatrix[i] + threatMatrix[i]
                                    : 0);
                            System.out.print((sum >= 0 ? " " : "") + formatter.format(sum) + " ");
                        }
                        System.out.println("\n");
                    }
                }

                return;
            }

            // move units
            for (AbstractUnit unit : controller.getUnitsByPlayerId(getPlayerId())) {
                if (unit.getData().getMovesLeft() < 1)
                    continue;
                Vector2[] adjacent = HexMap.getAdjacent((int) unit.getView().getBoardPosition().x,
                        (int) unit.getView().getBoardPosition().y);
                Vector2 finalPos = new Vector2(unit.getView().getBoardPosition());
                float finalSum = goalMatrix[(int) finalPos.y * controller.getMap().getWidth()
                        + (int) finalPos.x]
                        + valueMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x]
                        + threatMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x];
                for (Vector2 v : adjacent) {
                    if (v.x < 0 || v.x >= controller.getMap().getWidth() || v.y < 0
                            || v.y >= controller.getMap().getHeight())
                        continue;
                    float curSum = goalMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x]
                            + valueMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x]
                            + threatMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x];
                    if (curSum > finalSum && controller.isBoardPosEmpty(v)) {
                        finalPos.set(v);
                        finalSum = curSum;
                    }
                }
                if (finalPos.x != unit.getView().getBoardPosition().x
                        || finalPos.y != unit.getView().getBoardPosition().y) {
                    // move!
                    Move mv = new Move();
                    mv.owner = getPlayerId();
                    mv.turn = controller.getGameTurn();
                    mv.unit = unit.getId();
                    mv.toLocation = finalPos;
                    netController.sendAICommand(mv);
                    valueMatrix = null;
                    threatMatrix = null;
                    return;
                }
            }

            // attack
            Array<AbstractUnit> visibleUnits = new Array<AbstractUnit>();
            Array<AbstractUnit> friendlyUnits = controller.getUnitsByPlayerId(this.getPlayerId());
            for (AbstractUnit unit : controller.getUnits()) {
                if (unit.getOwner() == this || unit.getOwner() == null)
                    continue;
                if (visibilityMatrix[(int) (unit.getView().getBoardPosition().y * controller.getMap().getWidth()
                        + unit.getView().getBoardPosition().x)] && !unit.getData().isInvisible()
                        || controller.getMap().detectorCanSee(this, friendlyUnits,
                                unit.getView().getBoardPosition())) {
                    visibleUnits.add(unit);
                }
            }
            for (AbstractUnit unit : controller.getUnitsByPlayerId(getPlayerId())) {
                if (unit.getData().getAttacksLeft() < 1)
                    continue;
                AbstractUnit toAttack = null;
                float toAttackThreat = 0;
                for (AbstractUnit o : visibleUnits) {
                    float thisThreat = threatMatrix[controller.getMap().getWidth()
                            * (int) o.getView().getBoardPosition().y + (int) o.getView().getBoardPosition().x];
                    if (controller.getUnitManager().canAttack(unit, o)
                            && (toAttack == null || thisThreat > toAttackThreat)) {
                        toAttack = o;
                        toAttackThreat = thisThreat;
                    }
                }
                if (toAttack != null) {
                    //                        Gdx.app.log(LOG + "$attack", String.format("%s --> %s", unit.getProtoId(), toAttack.getProtoId()));
                    Attack at = new Attack();
                    at.owner = getPlayerId();
                    at.turn = controller.getGameTurn();
                    at.unit = unit.getId();
                    at.target = toAttack.getId();
                    netController.sendAICommand(at);
                    valueMatrix = null;
                    threatMatrix = null;
                    return;
                }
            }

            // build units // TODO build other than marines (ie: implement chromosome 11)

            int positionToBuild = -1;
            for (int i = 0; i < valueMatrix.length; i++) {
                if (visibilityMatrix[i]) {
                    float sum = threatMatrix[i] + valueMatrix[i] + goalMatrix[i];

                    if ((positionToBuild == -1 || valueMatrix[positionToBuild] + valueMatrix[positionToBuild]
                            + goalMatrix[positionToBuild] < sum)) {
                        //                                Gdx.app.log(LOG, i + ":" + controller.isBoardPosEmpty(
                        //                                        i % controller.getMap().getWidth(),
                        //                                        i / controller.getMap().getWidth()));
                        if (controller.isBoardPosEmpty(i % controller.getMap().getWidth(),
                                i / controller.getMap().getWidth())) {
                            positionToBuild = i;
                        }
                    }
                }
            }
            Prototypes.JsonProto unitToBuild = null;

            if (positionToBuild >= 0) {
                Vector2 buildPosition = new Vector2(positionToBuild % controller.getMap().getWidth(),
                        positionToBuild / controller.getMap().getWidth());
                Array<String> protoIds = new Array<String>();
                HashMap<String, Float> buildScores = new HashMap<String, Float>();
                for (Prototypes.JsonProto proto : Prototypes.getAll(getRace())) {
                    protoIds.add(proto.id);
                    if (proto.cost > 0) {
                        buildScores.put(proto.id, 0f);
                    }
                }

                for (AbstractUnit unit : controller.getUnits()) {
                    if (unit.getOwner() == this || !visibilityMatrix[(int) (unit.getView().getBoardPosition().y
                            * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)])
                        continue;

                    int unitIndex = protoIds.indexOf(unit.getProto().id, false);
                    int unitDistance = controller.getMap().getMapDist(unit.getView().getBoardPosition(),
                            buildPosition);
                    for (String key : buildScores.keySet()) {
                        buildScores.put(key, buildScores.get(key)
                                + ((Array<Float>) genome.chromosomes.get(10).genes.get(key)).get(unitIndex)
                                        / unitDistance);
                    }
                }

                String maxScore = null;
                float maxBuildScore = 0;
                while (unitToBuild == null && buildScores.keySet().size() > 0) {
                    for (String id : buildScores.keySet()) {
                        if (maxScore == null || buildScores.get(id) > buildScores.get(maxScore)) {
                            maxScore = id;
                            if (buildScores.get(id) > maxBuildScore) {
                                maxBuildScore = buildScores.get(id);
                            }
                        }
                    }

                    if (!maxScore.equals("saboteur") && buildScores.get(maxScore) > 0
                            && buildScores.get(maxScore) >= maxBuildScore
                                    - (Float) genome.chromosomes.get(10).genes.get("wait")
                            && getBankMoney() >= Prototypes.getProto(getRace(), maxScore).cost) {
                        unitToBuild = Prototypes.getProto(getRace(), maxScore);
                    } else {
                        buildScores.remove(maxScore);
                        maxScore = null;
                    }

                }
            }

            if (unitToBuild != null) {
                Build build = new Build();
                build.owner = getPlayerId();
                build.turn = controller.getGameTurn();
                build.building = unitToBuild.id;
                build.location = new Vector2(positionToBuild % controller.getMap().getWidth(),
                        positionToBuild / controller.getMap().getWidth());
                netController.sendAICommand(build);
                valueMatrix = null;
                return;
            }

            EndTurn et = new EndTurn();
            et.owner = getPlayerId();
            et.turn = controller.getGameTurn();
            netController.sendAICommand(et);
        }
    } else {
        visibilityMatrix = null;
        valueMatrix = null;
        threatMatrix = null;
        goalMatrix = null;
    }

}

From source file:com.badlogic.gdx.tests.box2d.Pyramid.java

License:Apache License

@Override
protected void createWorld(World world) {
    {/*from   w  w  w.ja  va 2  s . c om*/
        BodyDef bd = new BodyDef();
        Body ground = world.createBody(bd);

        EdgeShape shape = new EdgeShape();
        shape.set(new Vector2(-40, 0), new Vector2(40, 0));
        ground.createFixture(shape, 0.0f);
        shape.dispose();
    }

    {
        float a = 0.5f;
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(a, a);

        Vector2 x = new Vector2(-7.0f, 0.75f);
        Vector2 y = new Vector2();
        Vector2 deltaX = new Vector2(0.5625f, 1.25f);
        Vector2 deltaY = new Vector2(1.125f, 0.0f);

        for (int i = 0; i < 20; i++) {
            y.set(x);

            for (int j = i; j < 20; j++) {
                BodyDef bd = new BodyDef();
                bd.type = BodyType.DynamicBody;
                bd.position.set(y);
                Body body = world.createBody(bd);
                body.createFixture(shape, 5.0f);

                y.add(deltaY);
            }

            x.add(deltaX);
        }

    }
}

From source file:com.bladecoder.engine.util.PolygonUtils.java

License:Apache License

/**
 * Clamp the point to the nearest polygon segment
 * /*from   w  ww .  j  ava  2 s. co  m*/
 * @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;
}

From source file:com.calanti.androidnativekeyboardinputtest.libgdxModified_1_9_3.CalTextField.java

License:Apache License

private CalTextField findNextTextField(Array<Actor> actors, CalTextField best, Vector2 bestCoords,
        Vector2 currentCoords, boolean up) {
    for (int i = 0, n = actors.size; i < n; i++) {
        Actor actor = actors.get(i);//from   w w w. j  av  a 2  s  . c  o m
        if (actor == this)
            continue;
        if (actor instanceof CalTextField) {
            CalTextField textField = (CalTextField) 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 = (CalTextField) actor;
                    bestCoords.set(actorCoords);
                }
            }
        } else if (actor instanceof Group)
            best = findNextTextField(((Group) actor).getChildren(), best, bestCoords, currentCoords, up);
    }
    return best;
}

From source file:com.indignado.games.smariano.utils.dermetfan.box2d.Box2DUtils.java

License:Apache License

/** @see #positionRelative(com.badlogic.gdx.physics.box2d.CircleShape) */
public static Vector2 positionRelative(CircleShape shape, Vector2 output) {
    return output.set(shape.getPosition());
}

From source file:com.indignado.games.smariano.utils.dermetfan.box2d.Box2DUtils.java

License:Apache License

/** @see #position(com.badlogic.gdx.physics.box2d.Fixture) */
public static Vector2 position(Fixture fixture, Vector2 output) {
    return output.set(position(fixture.getShape(), fixture.getBody()));
}

From source file:com.indignado.games.smariano.utils.dermetfan.box2d.Box2DUtils.java

License:Apache License

/** @see #position(com.badlogic.gdx.physics.box2d.Shape, com.badlogic.gdx.physics.box2d.Body) */
public static Vector2 position(Shape shape, Body body, Vector2 output) {
    return output
            .set(body.getPosition().add(positionRelative(shape, body.getTransform().getRotation(), output)));
}

From source file:com.jmolina.orb.elements.LinearMagnetic.java

License:Open Source License

/**
 * Devuelve la fuerza que ejerce este elemento sobre un punto dado.
 *
 * La fuerza es cero si la proyeccin del punto sobre el eje del elemento cae fuera del segmento
 * del elemento.//w ww . j av  a 2  s.  c om
 *
 * @param point Punto expresado en unidades del mundo
 */
@Override
public Vector2 getForce(Vector2 point) {
    Vector2 force = new Vector2(0, 0);

    if (closeRange(point)) {
        if (insideField(point)) {
            float factor = MAX_FORCE * (getThreshold() - distanceLine(point)) / getThreshold();
            force.set(Utils.normal(getSegment()));
            force.scl(factor);

            if (getPolarity() == Polarity.REPULSIVE)
                force.scl(-1);
        }
    }

    return force;
}

From source file:com.jmolina.orb.elements.RadialMagnetic.java

License:Open Source License

/**
 * Devuelve la fuerza que ejerce este elemento sobre un punto dado.
 * <p>// w w w. j ava  2 s.c o m
 * La frmula de la atraccin est simplificada:
 * - Slo depende de la inversa de la distancia, siempre que el punto haya sobrepasado el umbral.
 * - Slo se computan los centroides (i.e. no se atrae el Orb si su centroide no cae dentro del
 * campo de actuacin).
 *
 * @param point Punto expresado en unidades del mundo
 */
@Override
public Vector2 getForce(Vector2 point) {
    Vector2 force = new Vector2(0, 0);

    if (belowThreshold(point)) {
        float factor = MAX_FORCE * (getThreshold() - distance(point)) / getThreshold();
        Vector2 direction = getPosition().sub(point).nor();
        force.set(direction).scl(factor);

        if (getPolarity() == Polarity.REPULSIVE)
            force.scl(-1);
    }

    return force;
}