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

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

Introduction

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

Prototype

public Vector2 add(float x, float y) 

Source Link

Document

Adds the given components to this vector

Usage

From source file:CB_Locator.Map.MapViewBase.java

License:Open Source License

public Vector2 worldToScreen(Vector2 point) {

    Vector2 result = new Vector2(0, 0);
    result.x = ((long) point.x - screenCenterW.x) / camera.zoom + (float) mapIntWidth / 2;
    result.y = -(-(long) point.y + screenCenterW.y) / camera.zoom + (float) mapIntHeight / 2;
    result.add(-(float) mapIntWidth / 2, -(float) mapIntHeight / 2);
    result.rotate(mapHeading);/*from w  w  w  .ja va2s .  com*/
    result.add((float) mapIntWidth / 2, (float) mapIntHeight / 2);
    return result;

}

From source file:CB_UI.GL_UI.Views.MapView.java

License:Open Source License

public void renderWPI(Batch batch, SizeF WpUnderlay, SizeF WpSize, WaypointRenderInfo wpi) {
    Vector2 screen = worldToScreen(new Vector2(wpi.MapX, wpi.MapY));

    screen.y -= ySpeedVersatz;//from ww w  .  j av a2  s  .co m
    // FIXME create a LineDrawable class for create one times and set the Coordinates with calculated Triangles
    if (myPointOnScreen != null && showDirectLine && (wpi.Selected)
            && (wpi.Waypoint == GlobalCore.getSelectedWaypoint())) {
        // FIXME render only if visible on screen (intersect the screen rec)
        Quadrangle line = new Quadrangle(myPointOnScreen.x, myPointOnScreen.y, screen.x, screen.y,
                3 * UI_Size_Base.that.getScale());
        if (paint == null) {
            paint = new GL_Paint();
            paint.setGLColor(Color.RED);
        }
        PolygonDrawable po = new PolygonDrawable(line.getVertices(), line.getTriangles(), paint,
                this.mapIntWidth, this.mapIntHeight);
        po.draw(batch, 0, 0, this.mapIntWidth, this.mapIntHeight, 0);
        po.dispose();
    }
    // Don't render if outside of screen !!
    if ((screen.x < 0 - WpSize.width || screen.x > this.getWidth() + WpSize.height)
            || (screen.y < 0 - WpSize.height || screen.y > this.getHeight() + WpSize.height)) {
        if (wpi.Cache != null && (wpi.Cache.Id == infoBubble.getCacheId()) && infoBubble.isVisible()) {
            // check if wp selected
            if (wpi.Waypoint != null && wpi.Waypoint.equals(infoBubble.getWaypoint())
                    || wpi.Waypoint == null && infoBubble.getWaypoint() == null)
                infoBubble.setInvisible();
        }
        return;
    }

    float NameYMovement = 0;

    if ((aktZoom >= zoomCross) && (wpi.Selected) && (wpi.Waypoint == GlobalCore.getSelectedWaypoint())) {
        // Draw Cross and move screen vector
        Sprite cross = Sprites.MapOverlay.get(3);
        cross.setBounds(screen.x - WpUnderlay.halfWidth, screen.y - WpUnderlay.halfHeight, WpUnderlay.width,
                WpUnderlay.height);
        cross.draw(batch);

        screen.add(-WpUnderlay.width, WpUnderlay.height);
        NameYMovement = WpUnderlay.height;
    }

    if (wpi.UnderlayIcon != null) {
        wpi.UnderlayIcon.setBounds(screen.x - WpUnderlay.halfWidth, screen.y - WpUnderlay.halfHeight,
                WpUnderlay.width, WpUnderlay.height);
        wpi.UnderlayIcon.draw(batch);
    }
    if (wpi.Icon != null) {
        wpi.Icon.setBounds(screen.x - WpSize.halfWidth, screen.y - WpSize.halfHeight, WpSize.width,
                WpSize.height);
        wpi.Icon.draw(batch);
    }

    // draw Favorite symbol
    if (wpi.Cache != null && wpi.Cache.isFavorite()) {
        batch.draw(Sprites.getSprite(IconName.favorit.name()), screen.x + (WpSize.halfWidth / 2),
                screen.y + (WpSize.halfHeight / 2), WpSize.width, WpSize.height);
    }

    if (wpi.OverlayIcon != null) {
        wpi.OverlayIcon.setBounds(screen.x - WpUnderlay.halfWidth, screen.y - WpUnderlay.halfHeight,
                WpUnderlay.width, WpUnderlay.height);
        wpi.OverlayIcon.draw(batch);
    }

    boolean drawAsWaypoint = wpi.Waypoint != null;

    // Rating des Caches darstellen
    if (wpi.Cache != null && showRating && (!drawAsWaypoint) && (wpi.Cache.Rating > 0) && (aktZoom >= 15)) {
        Sprite rating = Sprites.MapStars.get((int) Math.min(wpi.Cache.Rating * 2, 5 * 2));
        rating.setBounds(screen.x - WpUnderlay.halfWidth,
                screen.y - WpUnderlay.halfHeight - WpUnderlay.Height4_8, WpUnderlay.width,
                WpUnderlay.Height4_8);
        rating.setOrigin(WpUnderlay.width / 2, WpUnderlay.Height4_8 / 2);
        rating.setRotation(0);
        rating.draw(batch);
        NameYMovement += WpUnderlay.Height4_8;
    }

    // Beschriftung
    if (wpi.Cache != null && showTitles && (aktZoom >= 15)) {
        try {
            String Name = drawAsWaypoint ? wpi.Waypoint.getTitle() : wpi.Cache.getName();

            if (layout == null)
                layout = new GlyphLayout(Fonts.getNormal(), Name);
            else
                layout.setText(Fonts.getNormal(), Name);

            float halfWidth = layout.width / 2;
            Fonts.getNormal().draw(batch, layout, screen.x - halfWidth,
                    screen.y - WpUnderlay.halfHeight - NameYMovement);
        } catch (Exception e) {
        }
    }

    // Show D/T-Rating
    if (wpi.Cache != null && showDT && (!drawAsWaypoint) && (aktZoom >= 15)) {
        Sprite difficulty = Sprites.MapStars.get((int) Math.min(wpi.Cache.getDifficulty() * 2, 5 * 2));
        difficulty.setBounds(screen.x - WpUnderlay.width - GL_UISizes.infoShadowHeight,
                screen.y - (WpUnderlay.Height4_8 / 2), WpUnderlay.width, WpUnderlay.Height4_8);
        difficulty.setOrigin(WpUnderlay.width / 2, WpUnderlay.Height4_8 / 2);
        difficulty.setRotation(90);
        difficulty.draw(batch);

        Sprite terrain = Sprites.MapStars.get((int) Math.min(wpi.Cache.getTerrain() * 2, 5 * 2));
        terrain.setBounds(screen.x + GL_UISizes.infoShadowHeight, screen.y - (WpUnderlay.Height4_8 / 2),
                WpUnderlay.width, WpUnderlay.Height4_8);
        terrain.setOrigin(WpUnderlay.width / 2, WpUnderlay.Height4_8 / 2);
        terrain.setRotation(90);
        terrain.draw(batch);

    }

    if (wpi.Cache != null && (wpi.Cache.Id == infoBubble.getCacheId()) && infoBubble.isVisible()) {
        if (infoBubble.getWaypoint() == wpi.Waypoint) {
            Vector2 pos = new Vector2(screen.x - infoBubble.getHalfWidth(), screen.y);
            infoBubble.setPos(pos);
        }
    }
}

From source file:com.agateau.ui.anchor.PositionRule.java

License:Apache License

@Override
public void apply() {
    // Compute reference position
    Vector2 referencePos = new Vector2(reference.getWidth() * referenceAnchor.hPercent,
            reference.getHeight() * referenceAnchor.vPercent);

    Vector2 stagePos = reference.localToStageCoordinates(referencePos);

    // Apply space
    stagePos.add(hSpace, vSpace);

    // Position target (use target parent because setPosition() works in parent coordinates)
    Actor targetParent = target.getParent();
    if (targetParent == null) {
        return;//from  w ww.ja va2s  .c om
    }
    Vector2 targetPos = targetParent.stageToLocalCoordinates(stagePos);

    // Apply target offset (If right-aligned, hPercent is 100% => -width * scale.
    // If centered, hPercent is 50% => -width * scale / 2)
    targetPos.add(-target.getWidth() * target.getScaleX() * targetAnchor.hPercent,
            -target.getHeight() * target.getScaleY() * targetAnchor.vPercent);

    //noinspection SuspiciousNameCombination
    target.setPosition(MathUtils.floor(targetPos.x), MathUtils.floor(targetPos.y));
}

From source file:com.ahsgaming.valleyofbones.screens.AbstractScreen.java

License:Apache License

public static Vector2 localToGlobal(Vector2 local, Actor actor) {
    Vector2 coords = new Vector2(local);
    Actor cur = actor;/*  w  w w.  ja v a2  s  . co  m*/
    while (cur.getParent() != null) {
        coords.add(cur.getX(), cur.getY());
        cur = cur.getParent();
    }
    return coords;
}

From source file:com.badlogic.gdx.ai.tests.pfa.tests.tiled.hrchy.HierarchicalTiledGraph.java

License:Apache License

private HierarchicalTiledNode findFloorTileClosestToCenterOfMass(int level, int x0, int y0, int x1, int y1) {
    // Calculate center of mass
    Vector2 centerOfMass = new Vector2(0, 0);
    int floorTiles = 0;
    for (int x = x0; x < x1; x++) {
        for (int y = y0; y < y1; y++) {
            HierarchicalTiledNode n = getNodeAtLevel(level, x, y);
            if (n.type == FlatTiledNode.TILE_FLOOR) {
                centerOfMass.add(n.x, n.y);
                floorTiles++;//from ww w  . j  a  v a  2  s  .  c o m
            }
        }
    }
    int comx = (int) (centerOfMass.x / floorTiles);
    int comy = (int) (centerOfMass.y / floorTiles);
    HierarchicalTiledNode comTile = getNodeAtLevel(level, comx, comy);
    if (comTile.type == FlatTiledNode.TILE_FLOOR)
        return comTile;

    // Find floor tile closest to the center of mass
    float closetDist2 = Float.POSITIVE_INFINITY;
    HierarchicalTiledNode closestFloor = null;
    for (int x = x0; x < x1; x++) {
        for (int y = y0; y < y1; y++) {
            HierarchicalTiledNode n = getNodeAtLevel(level, x, y);
            if (n.type == FlatTiledNode.TILE_FLOOR) {
                float dist2 = Vector2.dst2(comTile.x, comTile.y, n.x, n.y);
                if (dist2 < closetDist2) {
                    closetDist2 = dist2;
                    closestFloor = n;
                }
            }
        }
    }

    return closestFloor;
}

From source file:com.github.fauu.helix.game.Game.java

License:Open Source License

public void handleInput(float delta) {
    Direction movementKeyPressedDirection = null;

    if (Gdx.input.isKeyPressed(Input.Keys.W)) {
        movementKeyPressedDirection = Direction.NORTH;
    } else if (Gdx.input.isKeyPressed(Input.Keys.S)) {
        movementKeyPressedDirection = Direction.SOUTH;
    } else if (Gdx.input.isKeyPressed(Input.Keys.A)) {
        movementKeyPressedDirection = Direction.WEST;
    } else if (Gdx.input.isKeyPressed(Input.Keys.D)) {
        movementKeyPressedDirection = Direction.EAST;
    }/* ww w. j av a  2 s .  c  o m*/

    if (movementKeyPressedDirection != null) {
        final Vector2 playerPosition = player.getPosition().cpy();
        Tile targetTile = null;

        switch (movementKeyPressedDirection) {
        case NORTH:
            targetTile = mapRegion.getTile(playerPosition.add(0, -1));
            break;
        case SOUTH:
            targetTile = mapRegion.getTile(playerPosition.add(0, 1));
            break;
        case WEST:
            targetTile = mapRegion.getTile(playerPosition.add(-1, 0));
            break;
        case EAST:
            targetTile = mapRegion.getTile(playerPosition.add(1, 0));
            break;
        }

        if (targetTile != null && targetTile.getType() != Tile.Type.DEFAULT_NONWALKABLE) {
            player.handleMovementInput(delta, movementKeyPressedDirection);
        } else if (!player.isMoving()) {
            player.setFacing(movementKeyPressedDirection);
        }
    }
}

From source file:com.github.unluckyninja.defenseofhuman.model.entity.Player.java

License:Open Source License

private void createBody(GameWorld gameWorld, Vector2 position) {
    Vector2 temp = new Vector2(position);
    if (body != null) {
        this.world.destroyBody(body);
    }/*  w w  w. j  a v a  2  s  . co m*/
    this.world = gameWorld.getWorld();

    BodyDef def = new BodyDef();
    def.type = BodyDef.BodyType.DynamicBody;
    def.fixedRotation = true;
    def.bullet = true;
    def.position.set(temp);
    body = world.createBody(def);

    body.setUserData(this);

    CircleShape cir = new CircleShape();
    cir.setRadius(0.4f);
    cir.setPosition(temp.add(0, 0.4f));
    circle = body.createFixture(cir, 0);
    circle.setRestitution(0f);
    cir.dispose();

    PolygonShape poly = new PolygonShape();
    poly.setAsBox(0.4f, 0.8f, temp.add(0, 0.8f), 0);
    box = body.createFixture(poly, 1);

    poly.setAsBox(0.2f, 0.2f, temp.add(0, -0.4f), 0);
    localLaunchPosition = temp.cpy();

    FixtureDef fixDef = new FixtureDef();
    fixDef.isSensor = true;
    fixDef.density = 0.01f;
    fixDef.shape = poly;

    shootSensor = body.createFixture(fixDef);

    poly.dispose();
}

From source file:com.kotcrab.vis.editor.module.physicseditor.input.EditionInputProcessor.java

License:Apache License

@Override
public void touchDragged(InputEvent event, float x, float y, int pointer) {
    if (!touchDown)
        return;/*from   w  w w  .  j a va2s  .c  o m*/

    RigidBodyModel model = screen.getSelectedModel();
    if (model == null)
        return;

    if (draggedPoint != null) {
        Vector2 p = cameraModule.alignedScreenToWorld(x, y);
        model.clearPhysics();

        float dx = p.x - draggedPoint.x;
        float dy = p.y - draggedPoint.y;
        draggedPoint.add(dx, dy);

        for (int i = 0; i < screen.selectedPoints.size(); i++) {
            Vector2 sp = screen.selectedPoints.get(i);
            if (sp != draggedPoint)
                sp.add(dx, dy);
        }

    } else {
        screen.mouseSelectionP2 = cameraModule.screenToWorld(x, y);
    }
}

From source file:com.mygdx.game.Sprites.Boss.Boss.java

private void defineRollingBoss() {
    Vector2 position = new Vector2(b2body.getPosition());
    world.destroyBody(b2body);/*from   w  w  w .  ja v  a2s . c o  m*/
    BodyDef bdef = new BodyDef();

    bdef.position.set(position.add(0, 1 / AdventureGame.PPM));
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body = world.createBody(bdef);

    FixtureDef fdef = new FixtureDef();

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(51 / AdventureGame.PPM, 10 / AdventureGame.PPM);

    fdef.isSensor = true;
    fdef.shape = shape;
    fdef.friction = 0;
    fdef.filter.categoryBits = AdventureGame.BOSS_BIT;

    fdef.filter.maskBits = AdventureGame.BULLET_BIT | AdventureGame.PLAYER_BIT | AdventureGame.DYNAMITE_BIT
            | AdventureGame.GROUND_BIT | AdventureGame.FLOOR_BIT;

    b2body.createFixture(fdef).setUserData(this);
    fdef.isSensor = false;
    EdgeShape downShape = new EdgeShape();
    downShape.set(-51 / AdventureGame.PPM, -12 / AdventureGame.PPM, 51 / AdventureGame.PPM,
            -12 / AdventureGame.PPM);
    fdef.shape = downShape;
    b2body.createFixture(fdef).setUserData(this);
    b2body.setLinearVelocity(-2, 0);
    stand = false;
}

From source file:com.ore.infinium.systems.MovementSystem.java

License:Open Source License

private void simulate(Entity entity, float delta) {
    //fixme maybe make a dropped component?
    if (controlMapper.get(entity) == null) {
        if (m_world.isServer()) {
            ItemComponent itemComponent = itemMapper.get(entity);
            if (itemComponent != null && itemComponent.state == ItemComponent.State.DroppedInWorld) {
                simulateDroppedItem(entity, delta);
            }/*from   ww w. j  av  a  2 s .c  o  m*/
        }

        return;
    }

    if (m_world.isServer()) {
        return;
    }

    //fixme handle noclip
    final SpriteComponent spriteComponent = spriteMapper.get(entity);
    final Vector2 origPosition = new Vector2(spriteComponent.sprite.getX(), spriteComponent.sprite.getY());

    final VelocityComponent velocityComponent = velocityMapper.get(entity);

    final Vector2 oldVelocity = new Vector2(velocityComponent.velocity);
    Vector2 newVelocity = new Vector2(oldVelocity);

    final Vector2 desiredDirection = controlMapper.get(entity).desiredDirection;

    //acceleration due to gravity
    Vector2 acceleration = new Vector2(desiredDirection.x * PlayerComponent.movementSpeed, World.GRAVITY_ACCEL);

    JumpComponent jumpComponent = jumpMapper.get(entity);
    if (jumpComponent.canJump && jumpComponent.shouldJump) {

        if (jumpComponent.jumpTimer.milliseconds() >= jumpComponent.jumpInterval) {
            //good to jump, actually do it now.
            jumpComponent.jumpTimer.reset();

            acceleration.y = -PlayerComponent.jumpVelocity;
        }
    }

    jumpComponent.canJump = false;
    jumpComponent.shouldJump = false;

    newVelocity = newVelocity.add(acceleration.x * delta, acceleration.y * delta);

    final float epsilon = 0.00001f;
    if (Math.abs(newVelocity.x) < epsilon && Math.abs(newVelocity.y) < epsilon) {
        //gets small enough velocity, cease movement/sleep object.
        newVelocity.set(0.0f, 0.0f);
    }

    newVelocity.x *= 0.8f;

    //    newVelocity = glm::clamp(newVelocity, glm::vec2(-maxMovementSpeed, PLAYER_JUMP_VELOCITY), glm::vec2(maxMovementSpeed, 9999999999999));//(9.8f / PIXELS_PER_METER) * 4.0));
    //    newVelocity = glm::clamp(newVelocity, glm::vec2(-maxMovementSpeed, PLAYER_JUMP_VELOCITY), glm::vec2(maxMovementSpeed, (9.8f / PIXELS_PER_METER) * 4.0));

    //clamp both axes between some max/min values..
    Vector2 dt = new Vector2(delta, delta);
    //        newVelocity.x = MathUtils.clamp(newVelocity.x, -PlayerComponent.maxMovementSpeed, PlayerComponent.maxMovementSpeed);
    //        newVelocity.y = MathUtils.clamp(newVelocity.y, PlayerComponent.jumpVelocity, World.GRAVITY_ACCEL_CLAMP);

    ///////// velocity verlet integration
    // http://lolengine.net/blog/2011/12/14/understanding-motion-in-games

    //HACK if i do 0.5f * delta, it doesn't move at all??
    // * delta
    //OLD CODE desiredPosition = ((origPosition.xy() + (oldVelocity + newVelocity)) * glm::vec2(0.5f) * dt);

    //TODO: add threshold to nullify velocity..so we don't infinitely move and thus burn through ticks/packets

    velocityComponent.velocity.set(newVelocity.x, newVelocity.y);

    // newVelocity is now invalid, note.
    Vector2 desiredPosition = origPosition.add(oldVelocity.add(newVelocity.scl(0.5f * delta)));
    final Vector2 finalPosition = performCollision(desiredPosition, entity);

    spriteComponent.sprite.setPosition(finalPosition.x, finalPosition.y);
    //        Gdx.app.log("player pos", finalPosition.toString());

    //FIXME: do half-ass friction, to feel better than this. and then when movement is close to 0, 0 it.
}