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

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

Introduction

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

Prototype

@Override
    public float dst(Vector2 v) 

Source Link

Usage

From source file:com.vlaaad.dice.game.actions.imp.ChainLightning.java

License:Open Source License

public static Array<Creature> findTargets(Creature creature, Creature.CreatureRelation relation, int x, int y,
        World world, int distance) {
    Vector2 creaturePos = tmp1.set(x, y);
    Array<Creature> result = new Array<Creature>();
    for (WorldObject object : world) {
        if (!(object instanceof Creature))
            continue;
        if (object.getX() == x && object.getY() == y)
            continue;

        Creature check = (Creature) object;
        if (!check.get(Attribute.canBeSelected) || !creature.inRelation(relation, check))
            continue;
        Vector2 checkPos = tmp2.set(check.getX(), check.getY());
        if (checkPos.dst(creaturePos) > distance)
            continue;
        result.add(check);// www .j  a  va2  s .co  m
    }
    return result;
}

From source file:com.vlaaad.dice.game.actions.imp.ClericDefence.java

License:Open Source License

public static Array<Creature> findTargets(Creature creature, Creature.CreatureRelation relation, int x, int y,
        World world, float distance) {
    Vector2 creaturePos = tmp1.set(x, y);
    Array<Creature> result = new Array<Creature>();
    for (WorldObject object : world) {
        if (!(object instanceof Creature))
            continue;
        Creature check = (Creature) object;
        if (!check.get(Attribute.canBeSelected) || !creature.inRelation(relation, check))
            continue;

        Vector2 checkPos = tmp2.set(check.getX(), check.getY());
        if (checkPos.dst(creaturePos) > distance)
            continue;
        result.add(check);/*from w w  w  .  j  ava2 s  .  c o  m*/
    }
    return result;
}

From source file:com.vlaaad.dice.game.actions.imp.Fireball.java

License:Open Source License

public static Array<Creature> findTargets(Creature creature, Creature.CreatureRelation relation, int x, int y,
        World world, int distance) {
    Vector2 creaturePos = tmp1.set(x, y);
    Array<Creature> result = new Array<Creature>();
    for (WorldObject object : world) {
        if (!(object instanceof Creature))
            continue;
        Creature check = (Creature) object;
        if (!check.get(Attribute.canBeSelected) || !creature.inRelation(relation, check))
            continue;
        Vector2 checkPos = tmp2.set(check.getX(), check.getY());
        if (checkPos.dst(creaturePos) > distance)
            continue;
        result.add(check);// w  ww .  j  a  v  a 2s.c o m
    }
    return result;
}

From source file:com.vlaaad.dice.game.actions.imp.PoisonShot.java

License:Open Source License

public static Array<Creature> findTargets(Creature creature, Creature.CreatureRelation relation, int x, int y,
        World world, float distance) {
    Vector2 creaturePos = tmp1.set(x, y);
    Array<Creature> result = new Array<Creature>();
    for (WorldObject object : world) {
        if (!(object instanceof Creature))
            continue;
        Creature check = (Creature) object;
        if (!check.get(Attribute.canBeSelected) || !creature.inRelation(relation, check))
            continue;
        if (check.hasEffect(PoisonEffect.class))
            continue;
        Vector2 checkPos = tmp2.set(check.getX(), check.getY());
        if (checkPos.dst(creaturePos) > distance)
            continue;
        result.add(check);//from   w w  w  .j a v  a  2  s .  com
    }
    return result;
}

From source file:com.vlaaad.dice.game.actions.imp.Shot.java

License:Open Source License

public static Array<Creature> findTargets(Creature creature, Creature.CreatureRelation relation, int x, int y,
        World world, float distance) {
    Vector2 creaturePos = tmp1.set(x, y);
    Array<Creature> result = new Array<Creature>();
    for (WorldObject object : world) {
        if (!(object instanceof Creature))
            continue;
        Creature check = (Creature) object;
        if (!check.get(Attribute.canBeSelected) || !creature.inRelation(relation, check))
            continue;
        Vector2 checkPos = tmp2.set(check.getX(), check.getY());
        if (checkPos.dst(creaturePos) > distance)
            continue;
        result.add(check);/*www.j  av a 2  s  .  c o m*/
    }
    return result;
}

From source file:com.vlaaad.dice.game.world.view.visualizers.ChainLightningVisualizer.java

License:Open Source License

@Override
public IFuture<Void> visualize(final ChainLightningResult result) {
    final Future<Void> future = new Future<Void>();
    final WorldObjectView casterView = visualizer.viewController.getView(result.caster);
    //        Logger.log(Config.findRegions("animation/chain-lightning"));
    final AnimationSubView appear = new AnimationSubView(0.05f, Config.findRegions("animation/chain-lightning"),
            Animation.PlayMode.NORMAL);//  w w  w.  ja  v a2  s  .  c  o m
    visualizer.viewController.scroller.centerOn(result.chain.first());
    casterView.addSubView(appear);
    casterView.addListener(new AnimationListener() {
        @Override
        protected void onAnimationEvent(AnimationEvent event) {
            casterView.removeListener(this);
            Array<Vector2> fullChain = new Array<Vector2>(result.chain.size + 1);
            fullChain.add(pointFor(result.caster, 19 / 24f, 23 / 24f));
            for (Creature target : result.chain) {
                fullChain.add(pointFor(target));
            }

            Array<Vector2> lightningPoints = new Array<Vector2>();
            lightningPoints.add(fullChain.first());
            for (int i = 1; i < fullChain.size; i++) {
                Vector2 from = fullChain.get(i - 1);
                Vector2 to = fullChain.get(i);
                int jogs = MathUtils.ceil(from.dst(to) * 1.3f / ViewController.CELL_SIZE);
                //add (from, to]
                if (jogs <= 0) {
                    lightningPoints.add(to);
                    continue;
                }
                Vector2 prev = from;
                for (int j = 1; j <= jogs; j++) {
                    float alpha = (float) j / (jogs + 1f);
                    Vector2 step = new Vector2(from).lerp(to, alpha);
                    float stepLength = tmp.set(prev).dst(step);
                    Vector2 target = tmp.set(to).sub(from).rotate(MathUtils.randomBoolean() ? -90 : 90).nor()
                            .scl(MathUtils.random(2f, stepLength / 2f)).add(step);
                    step.set(target);
                    lightningPoints.add(step);
                    prev = step;
                }
                lightningPoints.add(to);
            }
            for (Creature creature : result.chain) {
                final ParticleActor particles = new ParticleActor(
                        Config.particles.get("ability-chain-lightning-hit").obtain());
                particles.addListener(new ChangeListener() {
                    @Override
                    public void changed(ChangeEvent event, Actor actor) {
                        particles.effect.free();
                        particles.remove();
                    }
                });
                particles.setPosition((creature.getX() + 0.5f) * ViewController.CELL_SIZE,
                        (creature.getY() + 0.5f) * ViewController.CELL_SIZE);
                visualizer.viewController.effectLayer.addActor(particles);

                visualizer.viewController.visualize(new Defence(creature, AttackType.weapon));
            }
            final CountDown countDown = new CountDown(result.killed.size + 1, new Runnable() {
                @Override
                public void run() {
                    future.happen();
                }
            });
            for (Creature creature : result.killed) {
                if (creature == result.caster && result.addedExp.containsKey(result.caster))
                    continue;

                visualizer.viewController.visualize(new Death(result.caster, creature)).addListener(countDown);
            }
            SoundManager.instance.playSound("chain-lightning");
            for (int i = 1; i < lightningPoints.size; i++) {
                Vector2 from = lightningPoints.get(i - 1);
                Vector2 to = lightningPoints.get(i);
                SegmentActor ray = new SegmentActor(tmp.set(to).sub(from), "effect-chain-lightning-segment");
                ray.setPosition(from.x, from.y);
                visualizer.viewController.effectLayer.addActor(ray);
                ray.addAction(
                        Actions.sequence(Actions.delay(0.5f), Actions.alpha(0, 0.5f), Actions.removeActor()));
            }
            visualizer.viewController.effectLayer
                    .addAction(Actions.sequence(Actions.delay(0.5f), Actions.run(new Runnable() {
                        @Override
                        public void run() {
                            casterView.removeSubView(appear);
                            Array<TextureAtlas.AtlasRegion> appearRegions = Config
                                    .findRegions("animation/chain-lightning");
                            Array<TextureAtlas.AtlasRegion> disappearRegions = new Array<TextureAtlas.AtlasRegion>(
                                    appearRegions);
                            disappearRegions.removeIndex(1);
                            disappearRegions.reverse();
                            final AnimationSubView disappear = new AnimationSubView(0.1f, disappearRegions,
                                    Animation.PlayMode.NORMAL);
                            casterView.addSubView(disappear);
                            casterView.addListener(new AnimationListener() {
                                @Override
                                protected void onAnimationEvent(AnimationEvent event) {
                                    casterView.removeSubView(disappear);
                                    casterView.removeListener(this);
                                }
                            });
                        }
                    }), Actions.delay(0.5f), Actions.run(new Runnable() {
                        @Override
                        public void run() {
                            if (result.addedExp.size == 0) {
                                countDown.tick();
                                return;
                            }
                            //exp
                            GiveExpResult[] expResults = new GiveExpResult[result.addedExp.size];
                            int i = 0;
                            for (Creature creature : result.addedExp.keys()) {
                                expResults[i] = new GiveExpResult(creature, result.addedExp.get(creature, 0));
                                i++;
                            }
                            visualizer.visualize(new SequenceResult(expResults))
                                    .addListener(new IFutureListener<Void>() {
                                        @Override
                                        public void onHappened(Void aVoid) {
                                            countDown.tick();
                                            if (result.killed.contains(result.caster, true)
                                                    && result.addedExp.containsKey(result.caster)) {

                                                visualizer.viewController
                                                        .visualize(new Death(result.caster, result.caster))
                                                        .addListener(countDown);
                                            }
                                        }
                                    });
                        }
                    })));

        }
    });

    return future;
}

From source file:headmade.arttag.Guard.java

License:Apache License

public void update(ArtTagScreen artTag, float delta) {
    if (body == null) {
        return;//from   w  w  w. j a v  a  2 s. c o m
    }
    isRunning = isAlert || isCautious;
    moveSpeed = isRunning ? maxMoveSpeed * runFactor
            : isSuspicious ? maxMoveSpeed * 0.75f : isHeardPlayer ? 0.5f : maxMoveSpeed;
    final Vector2 oldMoveVec = targetMoveVec.cpy();

    Vector2 targetPoint = null;
    Float distanceToPlayer = null;
    if (isLightOn) {
        for (final Fixture fixture : playerInView) {
            targetPoint = fixture.getBody().getWorldCenter().cpy();
            final Vector2 diffVec = body.getWorldCenter().cpy().sub(targetPoint);
            boolean seesPlayer = false;
            distanceToPlayer = diffVec.len();
            if (distanceToPlayer < 1f) {
                seesPlayer = true;
            } else {
                final Vector2 outOfBodyVec = diffVec.scl(fixture.getShape().getRadius() * 1.01f);
                targetPoint.add(outOfBodyVec);
                seesPlayer = light.contains(targetPoint.x, targetPoint.y);
            }
            // Gdx.app.log(TAG, light.contains(targetPoint.x, targetPoint.y) + " diffVec.length " + diffVec.len());
            if (seesPlayer) {
                // Gdx.app.log(TAG, "Guard sees player");
                playerLastSeenVec = fixture.getBody().getWorldCenter().cpy();
                if (!isAlert) {
                    Assets.instance.playSound(AssetSounds.whosThere);
                }
                isAlert = true;
                Player.instance.isSpotted = true;
                reactionTime = 0f;
            } else {
                if (isAlert) {
                    Assets.instance.playSound(AssetSounds.huh);
                    reactionTime = MAX_REACTION_TIME;
                    isCautious = true;
                }
                isAlert = false;
            }
        }
    }

    // handle hearing
    if (Player.instance.isRunning && (Player.instance.isMoveDown || Player.instance.isMoveUp
            || Player.instance.isMoveLeft || Player.instance.isMoveRight) && null != Player.instance.body) {
        if (distanceToPlayer == null) {
            distanceToPlayer = body.getWorldCenter().cpy().sub(Player.instance.body.getWorldCenter()).len();
        }
        if (distanceToPlayer < MAX_LIGHT_CONE_LENGTH * 0.9f) {
            sumDeltaSinceHeardPlayer = 0;

            final RayCastCallback callback = new RayCastCallback() {
                @Override
                public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
                    // Gdx.app.log(TAG, "reportRayFixture " + point + " normal " + normal);
                    if (fixture.isSensor()) {
                        // Gdx.app.log(TAG, "Raycast ignoring sensor");
                        return 1;
                    }
                    if (body.equals(fixture.getBody())) {
                        // this is the guards body so there is nothing inbetween them
                        // Gdx.app.log(TAG, "Guard CAN see the point where the noise happened" + Player.instance.body.getWorldCenter());
                        // playerLastHeardVisibleVec = Player.instance.body.getWorldCenter().cpy();
                        return 1;
                    }
                    // Gdx.app.log(TAG, "Fall through");
                    isHearingObstructed = true;
                    return 0;
                }
            };
            try {
                isSuspicious = true;
                playerLastHeardVec = Player.instance.body.getWorldCenter().cpy();
                isHearingObstructed = false;
                // Gdx.app.log(TAG, "###################################");
                // Gdx.app.log(TAG, "Guard " + body.getWorldCenter());
                // Gdx.app.log(TAG, "Player " + playerLastHeardVec);
                artTag.world.rayCast(callback, playerLastHeardVec, body.getWorldCenter());
                if (!isHearingObstructed) {
                    playerLastHeardVisibleVec = Player.instance.body.getWorldCenter().cpy();
                }
            } catch (final Exception e) {
                Gdx.app.error(TAG, "Error Raycasting :(", e);
            }
        } else {
            sumDeltaSinceHeardPlayer += delta;
        }
    } else {
        sumDeltaSinceHeardPlayer += delta;
    }
    isHeardPlayer = playerLastHeardVisibleVec != null || sumDeltaSinceHeardPlayer < 3;

    if (isTouchingPlayerLightCone && Player.instance.isLightOn) {
        // isAlert = true;
    }

    // handle backToPath
    if (isAlert || isCautious || (isSuspicious && playerLastHeardVisibleVec != null)) {
        if (lastVisibleVecBackToPath == null) {
            lastVisibleVecBackToPath = body.getWorldCenter();
        }

        Vector2 checkPoint = path.get(currentPathIndex);
        if (backToPath.size > 0) {
            checkPoint = backToPath.get(backToPath.size - 1);
        }
        if (BODY_RADIUS < checkPoint.dst(body.getWorldCenter())) {
            // not touching checkpoint
            // Gdx.app.log(TAG, "Goard not touching checkpoint");
            final RayCastCallback callback = new RayCastCallback() {
                @Override
                public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
                    // Gdx.app.log(TAG, "reportRayFixture adds new backToPathPoint" + lastVisibleVecBackToPath);
                    backToPath.add(lastVisibleVecBackToPath.cpy());
                    return 0;
                }
            };
            try {
                artTag.world.rayCast(callback, body.getWorldCenter(), checkPoint);
            } catch (final Exception e) {
                Gdx.app.error(TAG, "Error Raycasting :(", e);
            }
        }
        lastVisibleVecBackToPath = body.getWorldCenter();
    }

    // determine targetPoint
    if (isAlert && playerInView.size > 0 && Player.instance.body != null) {
        targetPoint = Player.instance.body.getWorldCenter();
    } else if (isCautious && playerLastSeenVec != null) {
        targetPoint = playerLastSeenVec;
        if (BODY_RADIUS / 10 > targetPoint.dst2(body.getPosition())) {
            // Lost player
            Assets.instance.playSound(AssetSounds.hm);
            Gdx.app.log(TAG, "Guard no longer cautious");
            isCautious = false;
            isSuspicious = true;
        }
    } else if (isSuspicious && playerLastHeardVisibleVec != null) {
        targetPoint = playerLastHeardVisibleVec;
        // Gdx.app.log(TAG, "Guard going to playerLastHeardVisibleVec");
        if (BODY_RADIUS / 10 > targetPoint.dst2(body.getPosition())) {
            // Lost player
            Assets.instance.playSound(AssetSounds.hm);
            Gdx.app.log(TAG, "Guard no longer suspicious");
            isSuspicious = false;
            playerLastHeardVisibleVec = null;
        }
    } else {
        lastVisibleVecBackToPath = null;
        if (backToPath.size > 0) {
            // following Path back to path
            targetPoint = backToPath.get(backToPath.size - 1);
            if (BODY_RADIUS / 10 > targetPoint.dst(body.getPosition())) {
                // Gdx.app.log(TAG, "Guard reached target back to path point " + targetPoint);
                backToPath.pop();
            }
        } else {
            // following path
            isSuspicious = false;
            targetPoint = path.get(currentPathIndex);
            if (BODY_RADIUS > targetPoint.dst(body.getPosition())) {
                // Gdx.app.log(TAG, "Guard reached target point " + targetPoint);
                currentPathIndex++;
                if (currentPathIndex >= path.size) {
                    currentPathIndex = 0;
                }
                targetPoint = path.get(currentPathIndex);
                // Gdx.app.log(TAG, "New target point " + targetPoint);
            }
        }

    }

    targetMoveVec = targetPoint.cpy().sub(body.getPosition());
    targetMoveVec.nor().scl(moveSpeed);

    if (MathUtils.isEqual(0f, oldMoveVec.angle(targetMoveVec))) {
        sumDeltaSinceMoveChange += delta;
    } else {
        // movment direction changed
        sumDeltaSinceMoveChange = 0f;
    }

    final float alpha = reactionTime > 0 ? MathUtils.clamp(sumDeltaSinceMoveChange / reactionTime, 0.1f, 1f)
            : 1f;
    body.setLinearVelocity(targetMoveVec);

    final Vector2 bodyRotVec = new Vector2(1f, 0f);
    bodyRotVec.setAngleRad(body.getAngle());
    float angleDiff;
    if (!isAlert && !isSuspicious && isHeardPlayer && null == playerLastHeardVisibleVec
            && null != playerLastHeardVec) {
        // look at last heard
        angleDiff = bodyRotVec.angleRad(playerLastHeardVec.cpy().sub(body.getWorldCenter()).rotate90(-1));
    } else {
        angleDiff = bodyRotVec.angleRad(targetMoveVec.cpy().rotate90(-1));
    }
    final float rotByRad = MathUtils.clamp(angleDiff, -(MAX_ROTATION_SPEED * delta) / reactionTime,
            MAX_ROTATION_SPEED * delta / reactionTime);
    // Gdx.app.log(TAG, "angleDiff: " + angleDiff + " rotByRad: " + rotByRad + " bodyRotVec: " + bodyRotVec + " - targetMoveVec:
    // "
    // + targetMoveVec);

    // is moving?
    if (!MathUtils.isEqual(targetMoveVec.len2(), 0f)) {
        if (Player.instance.body != null) {
            final float dist = body.getPosition().dst(Player.instance.body.getPosition());
            float volume = isRunning ? STEP_VOLUME * 2 : STEP_VOLUME;
            if (dist > 1) {
                volume = volume / dist;
            }
            sound.setVolume(stepSoundId, volume);
            sound.setPitch(stepSoundId, isRunning ? runFactor : 1f);
            body.setTransform(body.getPosition(), body.getAngle() + rotByRad);
        }
    } else {
        sound.setVolume(stepSoundId, 0f);
        sound.setPitch(stepSoundId, 1f);
    }

    light.setActive(isLightOn);
}

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

License:Open Source License

@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {

    if (!_initialPointer1.equals(initialPointer1)) {
        _initialPointer1.set(initialPointer1);
        originalZoom = camera.zoom;//from  ww  w  .  ja v  a  2s.c o  m
    }
    if (!_initialPointer2.equals(initialPointer2)) {
        _initialPointer2.set(initialPointer2);
        originalZoom = camera.zoom;
    }
    setZoom(originalZoom * (initialPointer1.dst(initialPointer2)) / (pointer1.dst(pointer2)),
            v2.set(pointer1).add(pointer2).scl(0.5f));
    return true;
}

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

License:Open Source License

/**
 * create a polygon with the shape of a circle
 *//*  w w  w .  j  av a2  s  . c  om*/
public static Array<Vector2> makeCircle(Vector2 origin, float radius) {
    Vector2 v2 = new Vector2();
    Vector2 v3 = new Vector2();
    float verticeCount = (int) (36 + radius * 8);
    v2.set(radius, 0);
    // calculate number of segments and length of each segment
    float radiansPerSegment = 0;
    float segmentLength = 0;
    while (segmentLength < 0.05F && verticeCount > 5) {
        verticeCount--;
        radiansPerSegment = (float) (2 * Math.PI / verticeCount);
        v3.x = radius;
        v3.y = 0;
        v3.rotateRad(radiansPerSegment);
        segmentLength = v2.dst(v3);
    }
    Array<Vector2> vertices = new Array<Vector2>(true, (int) verticeCount, Vector2.class);
    for (int i = 0; i < verticeCount; i++) {
        v2.x = radius;
        v2.y = 0;
        v2.rotateRad(i * radiansPerSegment);
        v2.x += origin.x;
        v2.y += origin.y;
        vertices.add(new Vector2(v2));
    }
    return vertices;
}

From source file:org.ams.testapps.paintandphysics.cardhouse.TurnCircle.java

License:Open Source License

/** Whether v is outside the colored outline. */
public boolean isOutsideTurnCircle(Vector2 v) {
    if (!visible)
        return false;

    float dst = v.dst(position);
    boolean outside = dst > (radius + width) * zoom;

    if (debug)/*from  ww  w.  j  a v  a2  s.co m*/
        debug(outside ? v + " is outside circle." : v + " is not outside circle.");
    return outside;

}