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

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

Introduction

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

Prototype

@Override
    public Vector2 sub(Vector2 v) 

Source Link

Usage

From source file:jordanlw.gdxGame.Game.java

License:Open Source License

public void render() {
    Vector2 bulletVector = new Vector2();
    Vector2 relativeMousePosition = new Vector2();
    Vector2 distanceToMouse = new Vector2();
    Boolean gunFiredThisFrame = false;
    float delta = Gdx.graphics.getDeltaTime();
    movementThisFrame = false;/*  ww  w. ja  v  a 2s  . com*/

    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(0);
    handleEnemyWaves();

    //Handle player wanting to pause
    if (Gdx.input.isKeyJustPressed(Input.Keys.P)) {
        if (gamePaused) {
            if (!isGameCreated) {
                setupGame();
            }
            gamePaused = false;
            aMusicLibrary.backgroundMusic.play();
        } else {
            gamePaused = true;
            aMusicLibrary.backgroundMusic.pause();
        }
    }

    //Does the user want multiplayer?
    if (Gdx.input.isKeyJustPressed(Input.Keys.M)) {
        NetworkSetup.getTextInput("Multiplayer Network Address");
    }

    if (Gdx.input.isKeyJustPressed(Input.Keys.H)) {
        NetworkSetup.getAnswer("Host Multiplayer?");
    }

    if (!gamePaused) {
        totalTime += delta;
        for (Player player : players) {
            player.secondsDamaged -= delta;
        }
        //Update player rotation wrt mouse position
        getLocalPlayer().rotation = (float) Mouse
                .angleBetween(getLocalPlayer().position.getPosition(new Vector2()));

        Zombie.zombeGroanSoundTimer += delta;
        if (Zombie.zombeGroanSoundTimer > 6f) {
            int index = (int) (Math.random() * (aMusicLibrary.zombieSounds.length - 1));
            aMusicLibrary.zombieSounds[index].setVolume(aMusicLibrary.zombieSounds[index].play(),
                    0.5f * volume);
            Zombie.zombeGroanSoundTimer = 0;
        }

        handleInput(relativeMousePosition, mousePressedPosition, distanceToMouse, bulletVector);

        //Anything serverside eg. enemy movement, medkit respawning.
        if (isServer) {
            if (!aMusicLibrary.backgroundMusic.isPlaying()) {
                for (Player player : players) {
                    player.health = 0;
                }
            }
            for (Player player : players) {
                medkit.time += delta;
                if (medkit.time > Medkit.SECS_TILL_DISAPPEAR && medkit.health <= 0) {
                    medkit.health = Medkit.healthGiven;
                    medkit.position.setPosition((float) (camera.viewportWidth * Math.random()),
                            (float) (camera.viewportHeight * Math.random()));
                } else if (medkit.time >= Medkit.SECS_TILL_DISAPPEAR
                        && player.position.overlaps(medkit.position)) {
                    player.health += medkit.health;
                    medkit.health = 0;
                    medkit.time = 0;
                    aMusicLibrary.medkitSound.play(0.3f * volume);
                    if (player.health > 100) {
                        player.health = 100;
                    }
                }

                for (Zombie enemy : enemies) {
                    if (enemy.health <= 0) {
                        continue;
                    }
                    enemy.secondsDamaged -= delta;

                    Vector2 vecPlayer = new Vector2();
                    Vector2 vecEnemy = new Vector2();
                    enemy.position.getPosition(vecEnemy);
                    player.position.getPosition(vecPlayer);

                    Vector2 tmpEnemy = new Vector2(
                            vecPlayer.sub(vecEnemy).nor().scl(delta * enemy.walkingSpeed));
                    if (player.position.getPosition(new Vector2())
                            .dst(enemy.position.getPosition(new Vector2())) < 300) {
                        tmpEnemy.rotate(enemy.swarmAngle);
                    }

                    enemy.rotation = tmpEnemy.angle();
                    tmpEnemy.add(enemy.position.x, enemy.position.y);
                    enemy.position.setPosition(tmpEnemy);
                }
            }
        }
        //Respond to player pressing mouse button
        if (mousePressedPosition.x != -1 && mousePressedPosition.y != -1 && getLocalPlayer().health > 0) {
            //Gun sound for player
            if (totalTime > timeGunSound) {
                timeGunSound = totalTime + 0.5f;
                aMusicLibrary.gunSound.play(0.25f * volume);
                //aMusicLibrary.gunSound.setPitch(soundId, 1 + (long) (0.3f * Math.random()));
                gunFiredThisFrame = true;
                shootingTime = torsoAnimLength;
                Collections.sort(enemies, new ZombieDistance());
                for (Zombie enemy : enemies) {
                    if (enemy.health <= 0) {
                        continue;
                    }

                    Vector2 vecPlayer = new Vector2();
                    getLocalPlayer().position.getCenter(vecPlayer);

                    float angle = (float) Mouse.angleBetween(vecPlayer);
                    Vector2 vecAngle = new Vector2(vecPlayer);
                    Vector2 tmp = new Vector2(1, 1);
                    tmp.setAngle(angle).nor().scl(98765);
                    vecAngle.add(tmp);

                    if (Intersector.intersectSegmentCircle(vecPlayer, vecAngle,
                            enemy.position.getCenter(new Vector2()),
                            (enemy.position.width / 2) * (enemy.position.width / 2))) {
                        enemy.secondsDamaged = 0.5f;
                        enemy.health -= 35;
                        if (enemy.health <= 0) {
                            gold.saveEnemy(currentWave, enemies.indexOf(enemy));
                        }
                        break;
                    }
                }
            }
        }
    }
    camera.update();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.setColor(Color.WHITE);
    for (int width = 0; width < windowSize.x; width += backgroundTexture.getWidth()) {
        for (int height = 0; height < windowSize.y; height += backgroundTexture.getHeight()) {
            batch.draw(backgroundTexture, width, height);
        }
    }
    medkit.draw(batch);
    gold.draw(batch);

    //Draw enemies
    for (Zombie enemy : enemies) {
        enemy.draw(batch, totalTime);
    }
    batch.setColor(Color.WHITE);

    for (Player player : players) {
        player.draw(batch, totalTime, delta);
    }

    if (getLocalPlayer().health <= 0) {
        batch.draw(gameOverTexture, camera.viewportWidth / 2 - gameOverTexture.getWidth() / 2,
                camera.viewportHeight / 2 - gameOverTexture.getHeight() / 2);
    } else if (gamePaused) {
        batch.draw(gameStartTexture, camera.viewportWidth / 2 - gameStartTexture.getWidth() / 2,
                camera.viewportHeight / 2 - gameStartTexture.getHeight() / 2);
    }

    batch.setColor(Color.YELLOW);
    if (gunFiredThisFrame) {
        //noinspection SuspiciousNameCombination
        batch.draw(singlePixel, getLocalPlayer().position.x, getLocalPlayer().position.y, 0, 0, 1, 1, 1,
                distanceToMouse.x, 180 + (float) Math.toDegrees(
                        Math.atan2((double) relativeMousePosition.x, (double) relativeMousePosition.y)));

    }
    batch.end();

    isLeftMousePressedThisFrame = false;
    mousePressedPosition.set(-1, -1);
}

From source file:MeshBoneUtil.MeshRenderRegion.java

License:Open Source License

public void runUvWarp() {
    int cur_uvs_index = getUVsIndex();
    for (int i = 0; i < uv_warp_ref_uvs.size(); i++) {
        Vector2 set_uv = uv_warp_ref_uvs.get(i).cpy();
        set_uv.sub(uv_warp_local_offset);
        set_uv.scl(uv_warp_scale);//w ww .  jav  a  2  s.c om
        set_uv.add(uv_warp_global_offset);

        /*
        set_uv -= uv_warp_local_offset;
        set_uv *= uv_warp_scale;
        set_uv += uv_warp_global_offset;
        */

        store_uvs[0 + cur_uvs_index] = set_uv.x;
        store_uvs[1 + cur_uvs_index] = set_uv.y;

        /*
        store_uvs[0 + cur_uvs_index] = (float)set_uv.X;
        store_uvs[1 + cur_uvs_index] = (float)set_uv.Y;
        */

        cur_uvs_index += 2;
    }
}

From source file:org.ams.core.CameraNavigator.java

License:Open Source License

/**
 * @param zoom    the cameras zoom will be set to this value.
 * @param screenX the screen x-coordinate you want to zoom in on(or away from).
 * @param screenY the screen y-coordinate you want to zoom in on(or away from).
 *//*from  ww  w.j  a  v a2 s .  c o m*/
public void setZoom(float zoom, float screenX, float screenY) {
    Vector2 touchWorldBefore = getPositionOfTouch(screenX, screenY);
    touchWorldBefore.add(camera.position.x, camera.position.y);

    camera.zoom = zoom;
    camera.update();

    Vector2 touchWorldAfter = getPositionOfTouch(screenX, screenY);
    touchWorldAfter.add(camera.position.x, camera.position.y);

    camera.translate(touchWorldBefore.sub(touchWorldAfter));
    camera.update();
}

From source file:org.ams.core.Util.java

License:Open Source License

/**
 * Translates given polygon so its centroid is now at the origin.
 *
 * @param vertices some polygon./*from w  w w  .  j  a v  a  2  s  . c  o m*/
 * @return the previous centroid.
 */
public static Vector2 translateSoCentroidIsAtOrigin(Array<Vector2> vertices) {
    Vector2 centroid = Util.polygonCentroid(vertices);

    for (Vector2 v : vertices) {
        v.sub(centroid);
    }
    return centroid;
}

From source file:org.ams.prettypaint.OutlinePolygon.java

License:Open Source License

private void updateVertexDefault(int index, boolean inside) {

    BoundingBox box = boundingBoxes.items[index / verticesPerBox];
    box.needsCullingUpdate = true;/*from  w w w. j ava  2s  .  com*/

    int k = index % vertices.size;
    StripVertex stripVertex = vertexDataArray.items[k];
    AuxVertexFinder auxVertexFinder = this.auxVertexFinder;

    Array<Float> vertexData = inside ? stripVertex.insideVertexData : stripVertex.outsideVertexData;
    vertexData.clear();

    auxVertexFinder.setInsideStrip(inside);

    Vector2 currentVertex = vertices.items[k];
    Vector2 defaultAux = auxVertexFinder.getAux(vertices, k);

    boolean roundCorner = false;

    { // within these brackets i figure out if i should round the corner.
      // i hope to rewrite this code to something i can understand one day after writing it
        Vector2 previous = tmp.set(vertices.items[(k - 1 + vertices.size) % vertices.size]);
        Vector2 copyOfDefaultAux = tmp1.set(defaultAux);

        previous.sub(currentVertex);
        copyOfDefaultAux.sub(currentVertex);

        float angle = previous.angleRad() - copyOfDefaultAux.angleRad();
        angle = ((angle + MathUtils.PI2) % MathUtils.PI) * 2f;
        boolean angleMoreThanPI;
        if (inside) {
            angleMoreThanPI = angle > MathUtils.PI * 1.1f;
        } else {
            angleMoreThanPI = angle < MathUtils.PI * 0.9f;
        }

        if (auxVertexFinder.clockWisePolygon)
            angleMoreThanPI = !angleMoreThanPI;

        if (angleMoreThanPI) {
            boolean sharpCorner = Math.abs(MathUtils.PI - angle) > Math.PI * 0.4f;
            roundCorner = roundSharpCorners && sharpCorner;
        }
    }

    if (roundCorner) {
        Vector2 beginningAux = auxVertexFinder.getAuxEnding(vertices, k, 0);
        Vector2 endingAux = auxVertexFinder.getAuxBeginning(vertices, k, 0);
        Vector2 middleAux = tmp.set(defaultAux).sub(currentVertex).nor().scl(halfWidth).add(currentVertex);

        add(currentVertex, VERTEX_TYPE_USER, vertexData);
        add(beginningAux, VERTEX_TYPE_AUX, vertexData);

        add(currentVertex, VERTEX_TYPE_USER, vertexData);
        add(middleAux, VERTEX_TYPE_AUX, vertexData);

        add(currentVertex, VERTEX_TYPE_USER, vertexData);
        add(endingAux, VERTEX_TYPE_AUX, vertexData);
    } else {
        add(currentVertex, VERTEX_TYPE_USER, vertexData);
        add(defaultAux, VERTEX_TYPE_AUX, vertexData);
    }

}

From source file:org.ams.testapps.prettypaint.CircleAndBackground.java

License:Open Source License

/**
 * @param zoom    the cameras zoom will be set to this value.
 * @param screenX the screen x-coordinate you want to zoom in on(or away from).
 * @param screenY the screen y-coordinate you want to zoom in on(or away from).
 *//*  w w w.j  a  v  a2 s  . c o  m*/
public void setZoom(float zoom, int screenX, int screenY) {
    Vector2 touchWorldBefore = getPositionOfTouch(screenX, screenY);
    touchWorldBefore.add(camera.position.x, camera.position.y);

    camera.zoom = zoom;
    camera.update();

    Vector2 touchWorldAfter = getPositionOfTouch(screenX, screenY);
    touchWorldAfter.add(camera.position.x, camera.position.y);

    camera.translate(touchWorldBefore.sub(touchWorldAfter));
    camera.update();

}

From source file:org.ams.testapps.prettypaint.JaggedPolygon.java

License:Open Source License

/**
 * @param zoom    the cameras zoom will be set to this value.
 * @param screenX the screen x-coordinate you want to zoom in on(or away from).
 * @param screenY the screen y-coordinate you want to zoom in on(or away from).
 */// ww  w. j a v  a 2 s . c o m
public void setZoom(float zoom, int screenX, int screenY) {
    Vector2 touchWorldBefore = getPositionOfTouch(screenX, screenY);
    touchWorldBefore.add(camera.position.x, camera.position.y);

    camera.zoom = zoom;
    camera.update();

    Vector2 touchWorldAfter = getPositionOfTouch(screenX, screenY);
    touchWorldAfter.add(camera.position.x, camera.position.y);

    camera.translate(touchWorldBefore.sub(touchWorldAfter));
    camera.update();
}

From source file:org.destinationsol.CommonDrawer.java

License:Apache License

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);//from ww w.  ja va  2 s.c o  m
}

From source file:org.destinationsol.game.chunk.ChunkFiller.java

License:Apache License

/**
 * Add a bunch of a certain type of junk to the background layers furthest away.
 * <p/>/*from  w w  w .  j  a  va 2 s. c o  m*/
 * This type of junk does not move on its own, it merely changes position as the camera moves, simulating different
 * depths relative to the camera.
 *
 * @param game       The {@link SolGame} instance to work with
 * @param chCenter   The center of the chunk
 * @param remover
 * @param draLevel   The depth of the junk
 * @param conf       The environment configuration
 * @param densityMul A density multiplier. This will be multiplied with the density defined in the environment configuration
 */
private void fillFarJunk(SolGame game, Vector2 chCenter, RemoveController remover, DraLevel draLevel,
        SpaceEnvConfig conf, float densityMul) {
    if (conf == null)
        return;
    int count = getEntityCount(conf.farJunkDensity * densityMul);
    if (count == 0)
        return;

    ArrayList<Dra> dras = new ArrayList<Dra>();
    TextureManager textureManager = game.getTexMan();

    for (int i = 0; i < count; i++) {
        // Select a random far junk texture
        TextureAtlas.AtlasRegion tex = SolMath.elemRnd(conf.farJunkTexs);
        // Flip texture for every other piece of junk
        if (SolMath.test(.5f))
            tex = textureManager.getFlipped(tex);
        // Choose a random size (within a range)
        float sz = SolMath.rnd(.3f, 1) * FAR_JUNK_MAX_SZ;
        // Apply a random rotation speed
        float rotSpd = SolMath.rnd(FAR_JUNK_MAX_ROT_SPD);
        // Select a random position in the chunk centered around chCenter, relative to the position of the chunk.
        Vector2 junkPos = getRndPos(chCenter);
        junkPos.sub(chCenter);

        // Create the resulting sprite and add it to the list
        RectSprite s = new RectSprite(tex, sz, 0, 0, junkPos, draLevel, SolMath.rnd(180), rotSpd, SolColor.DDG,
                false);
        dras.add(s);
    }

    // Create a common FarDras instance for the pieces of junk and only allow the junk to be drawn when it's not hidden by a planet
    FarDras so = new FarDras(dras, new Vector2(chCenter), new Vector2(), remover, true);
    // Add the collection of objects to the object manager
    game.getObjMan().addFarObjNow(so);
}

From source file:org.destinationsol.game.chunk.ChunkFiller.java

License:Apache License

/**
 * Add specks of dust to the background layer closest to the front.
 * <p/>//from www.j  a  va  2s. c  o  m
 * Dust is fixed in the world and therefore moves opposite to the cameras movement.
 *
 * @param game     The {@link SolGame} instance to work with
 * @param chCenter The center of the chunk
 * @param remover
 */
private void fillDust(SolGame game, Vector2 chCenter, RemoveController remover) {
    ArrayList<Dra> dras = new ArrayList<Dra>();
    int count = getEntityCount(DUST_DENSITY);
    if (count == 0)
        return;

    TextureAtlas.AtlasRegion tex = myDustTex;
    for (int i = 0; i < count; i++) {
        // Select a random position in the chunk centered around chCenter, relative to the position of the chunk.
        Vector2 dustPos = getRndPos(chCenter);
        dustPos.sub(chCenter);
        // Create the resulting sprite and add it to the list
        RectSprite s = new RectSprite(tex, DUST_SZ, 0, 0, dustPos, DraLevel.DECO, 0, 0, SolColor.W, false);
        dras.add(s);
    }

    // Create a common FarDras instance for the specks of dust and only allow the dust to be drawn when it's not hidden by a planet
    FarDras so = new FarDras(dras, chCenter, new Vector2(), remover, true);
    game.getObjMan().addFarObjNow(so);
}