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

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

Introduction

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

Prototype

@Override
    public float len2() 

Source Link

Usage

From source file:AITest.Box2DSteeringEntity.java

private void applySteering(float delta) {
    boolean anyAccelerations = false;
    if (!steeringOutput.isZero()) {
        Vector2 force = steeringOutput.linear.scl(delta);
        body.applyForceToCenter(force, true);
        anyAccelerations = true;/*from   ww  w .  ja v a  2s .com*/
    }
    if (steeringOutput.angular != 0) {
        body.applyTorque(steeringOutput.angular * delta, true);
        anyAccelerations = true;
    }
    //        else { 
    //            Vector2 linVel = getLinearVelocity();
    //            if(!linVel.isZero())
    //            {
    //                float newOrientation = vectorToAngle(linVel);
    //                body.setAngularVelocity(newOrientation - getAngularVelocity() * delta);
    //                body.setTransform(body.getPosition(), newOrientation);
    //            }}

    if (anyAccelerations) {
        Vector2 velocity = body.getLinearVelocity();
        float currentSpeedSquare = velocity.len2();
        if (currentSpeedSquare > maxLinearSpeed * maxLinearSpeed) {
            body.setLinearVelocity(velocity.scl(maxLinearSpeed / (float) Math.sqrt(currentSpeedSquare)));
        }
        if (body.getAngularVelocity() > maxAngularSpeed) {
            body.setAngularVelocity(maxAngularSpeed);
        }
    }
}

From source file:com.badlogic.gdx.ai.tests.steer.box2d.Box2dSteeringEntity.java

License:Apache License

protected void applySteering(SteeringAcceleration<Vector2> steering, float deltaTime) {
    boolean anyAccelerations = false;

    // Update position and linear velocity.
    if (!steeringOutput.linear.isZero()) {
        Vector2 force = steeringOutput.linear.scl(deltaTime);
        body.applyForceToCenter(force, true);
        anyAccelerations = true;/*from  www  .jav a2  s. c  o m*/
    }

    // Update orientation and angular velocity
    if (isIndependentFacing()) {
        if (steeringOutput.angular != 0) {
            body.applyTorque(steeringOutput.angular * deltaTime, true);
            anyAccelerations = true;
        }
    } else {
        // If we haven't got any velocity, then we can do nothing.
        Vector2 linVel = getLinearVelocity();
        if (!linVel.isZero(MathUtils.FLOAT_ROUNDING_ERROR)) {
            float newOrientation = vectorToAngle(linVel);
            body.setAngularVelocity((newOrientation - getAngularVelocity()) * deltaTime); // this is superfluous if independentFacing is always true
            body.setTransform(body.getPosition(), newOrientation);
        }
    }

    if (anyAccelerations) {
        // body.activate();

        // TODO:
        // Looks like truncating speeds here after applying forces doesn't work as expected.
        // We should likely cap speeds form inside an InternalTickCallback, see
        // http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Simulation_Tick_Callbacks

        // Cap the linear speed
        Vector2 velocity = body.getLinearVelocity();
        float currentSpeedSquare = velocity.len2();
        float maxLinearSpeed = getMaxLinearSpeed();
        if (currentSpeedSquare > maxLinearSpeed * maxLinearSpeed) {
            body.setLinearVelocity(velocity.scl(maxLinearSpeed / (float) Math.sqrt(currentSpeedSquare)));
        }

        // Cap the angular speed
        float maxAngVelocity = getMaxAngularSpeed();
        if (body.getAngularVelocity() > maxAngVelocity) {
            body.setAngularVelocity(maxAngVelocity);
        }
    }
}

From source file:com.dongbat.invasion.system.EnemyMovementSystem.java

@Override
protected void process(Entity entity) {
    Delay delay = delayMapper.get(entity);
    if (delay != null && delay.getDuration() > 0) {
        long timePassed = TimeUtil.getGameTimeSince(delay.getStartTime());
        if (timePassed <= delay.getDuration()) {
            return;
        }//from  w  w w  .  ja v  a 2  s .c o m
    }

    //    Vector2 prevVelocity = PhysicsUtil.getVelocity(entity).cpy();
    Vector2 position = PhysicsUtil.getPosition(entity);
    EnemyMovement movement = EntityUtil.getComponent(entity, EnemyMovement.class);
    PhysicsUtil.setVelocity(entity, new Vector2());
    Vector2 intent = movement.getIntent().cpy();
    Vector2 travel;
    MovementUtil.moveEnemyTo(entity, intent);
    // TODO check free enemy
    intent.y = position.y;
    // TODO free movement unit use moveTo
    Vector2 distance = intent.cpy().sub(position);
    travel = PhysicsUtil.getVelocity(entity).cpy().scl(world.delta);
    if (travel.dot(distance) > 0 && travel.len2() - distance.len2() > 0) {
        PhysicsUtil.setPosition(entity, intent);
        PhysicsUtil.setVelocity(entity, new Vector2());
    }

    if (TimeUtil.getGameTimeSince(movement.getStartDrag()) >= movement.getDragDuration()) {
        movement.setDraggedTo(null);
    }

    if (movement.getDraggedTo() == null) {
        return;
    }

    float max = movement.getDraggedTo().cpy().sub(movement.getDraggedFrom()).len2();
    float actual = position.cpy().sub(movement.getDraggedFrom()).len2();
    if (actual >= max) {
        return;
    }

    Vector2 drag = movement.getDraggedTo().cpy().sub(position);
    float dragLen2 = drag.len2();
    if (dragLen2 > movement.getDragForce() * movement.getDragForce()) {
        drag.nor().scl(movement.getDragForce());
    }
    PhysicsUtil.applyImpulseOnEnemy(entity, drag);

    // TODO fix this similar to above
    travel = PhysicsUtil.getVelocity(entity).cpy().scl(world.delta);
    if (travel.sub(drag).len2() <= Constants.GAME.EPSILON_SQUARED) {
        PhysicsUtil.setPosition(entity, movement.getDraggedTo());
        PhysicsUtil.applyImpulseOnEnemy(entity, drag.scl(-1));
    }
}

From source file:com.hajnar.GravityShip.GameWorld.java

License:Apache License

public void updateBlackHoles(float delta) {
    int len = blackHoles.size();
    for (int i = 0; i < len; i++) {
        blackHoles.get(i).update(delta);
        Vector2 playerPosition = player.getBody().getPosition();
        Vector2 holePosition = blackHoles.get(i).getBody().getPosition();
        Vector2 gravityVector = (holePosition.sub(playerPosition));
        float gravityForce = blackHoles.get(i).getStrength() / gravityVector.len2();
        gravityVector.nor();//from w w w  .ja  v  a2s  .c o  m
        gravityVector.mul(gravityForce);
        player.getBody().applyForceToCenter(gravityVector);
    }
}

From source file:com.kotcrab.vis.editor.module.physicseditor.util.earclipping.bayazit.BayazitDecomposer.java

License:Apache License

public static Array<Vector2> ReduceByDistance(Array<Vector2> vertices, float distance) {
    // We can't simplify polygons under 3 vertices
    if (vertices.size < 3)
        return vertices;
    Array<Vector2> simplified = new Array<Vector2>();
    for (int i = 0; i < vertices.size; i++) {
        Vector2 current = vertices.get(i);
        int ii = i + 1;
        if (ii >= vertices.size)
            ii = 0;/*from  w  w w  .  j  a  v  a  2 s  . co  m*/
        Vector2 next = vertices.get(ii);
        Vector2 diff = new Vector2(next.x - current.x, next.y - current.y);
        // If they are closer than the distance, continue
        if (diff.len2() <= distance)
            continue;
        simplified.add(current);
    }
    return simplified;
}

From source file:com.kotcrab.vis.editor.module.physicseditor.util.PolygonUtils.java

License:Apache License

/** Checks whether polygon vertices will make degenerated box2d polygon or not */
public static boolean isDegenerate(Vector2[] vertices) {
    // https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d/jni/Box2D/Collision/Shapes/b2PolygonShape.cpp#L120-L226
    // it's not like I understand what is going on here

    int count = vertices.length;
    int n = Math.min(count, B2_MAX_VERTICES);

    // Perform welding and copy vertices into local buffer.
    Vector2[] ps = new Vector2[B2_MAX_VERTICES];
    int tempCount = 0;
    for (int i = 0; i < n; ++i) {
        Vector2 v = vertices[i];

        boolean unique = true;
        for (int j = 0; j < tempCount; ++j) {
            if (distanceSquared(v, ps[j]) < 0.5f * B2_LINEAR_SLOP) {
                unique = false;//from  ww  w . j av  a2  s.  c o  m
                break;
            }
        }

        if (unique) {
            ps[tempCount++] = v;
        }
    }

    n = tempCount;
    if (n < 3) {
        // Polygon is degenerate.
        return true;
    }

    // Create the convex hull using the Gift wrapping algorithm
    // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm

    // Find the right most point on the hull
    int i0 = 0;
    float x0 = ps[0].x;
    for (int i = 1; i < n; ++i) {
        float x = ps[i].x;
        if (x > x0 || (x == x0 && ps[i].y < ps[i0].y)) {
            i0 = i;
            x0 = x;
        }
    }

    int hull[] = new int[B2_MAX_VERTICES];
    int m = 0;
    int ih = i0;

    while (true) {
        hull[m] = ih;

        int ie = 0;
        for (int j = 1; j < n; ++j) {
            if (ie == ih) {
                ie = j;
                continue;
            }

            Vector2 r = ps[ie].cpy().sub(ps[hull[m]]);
            Vector2 v = ps[j].cpy().sub(ps[hull[m]]);

            float c = r.crs(v);
            if (c < 0.0f) {
                ie = j;
            }

            // Collinearity check
            if (c == 0.0f && v.len2() > r.len2()) {
                ie = j;
            }
        }

        ++m;
        ih = ie;

        if (ie == i0) {
            break;
        }
    }

    if (m < 3) {
        // Polygon is degenerate.
        return true;
    }

    return false;
}

From source file:com.kotcrab.vis.editor.util.polygon.PolygonUtils.java

License:Apache License

/** Checks whether polygon faces will make degenerated box2d polygon or not */
public static boolean isDegenerate(Vector2[] vertices) {
    // https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d/jni/Box2D/Collision/Shapes/b2PolygonShape.cpp#L120-L226
    // it's not like I understand what is going on here

    int count = vertices.length;
    int n = Math.min(count, B2_MAX_VERTICES);

    // Perform welding and copy vertices into local buffer.
    Vector2[] ps = new Vector2[B2_MAX_VERTICES];
    int tempCount = 0;
    for (int i = 0; i < n; ++i) {
        Vector2 v = vertices[i];

        boolean unique = true;
        for (int j = 0; j < tempCount; ++j) {
            if (distanceSquared(v, ps[j]) < ((0.5f * B2_LINEAR_SLOP) * (0.5f * B2_LINEAR_SLOP))) {
                unique = false;// w w w .  j  a  v  a 2s  . c  om
                break;
            }
        }

        if (unique) {
            ps[tempCount++] = v;
        }
    }

    n = tempCount;
    if (n < 3) {
        // Polygon is degenerate.
        return true;
    }

    // Create the convex hull using the Gift wrapping algorithm
    // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm

    // Find the right most point on the hull
    int i0 = 0;
    float x0 = ps[0].x;
    for (int i = 1; i < n; ++i) {
        float x = ps[i].x;
        if (x > x0 || (x == x0 && ps[i].y < ps[i0].y)) {
            i0 = i;
            x0 = x;
        }
    }

    int hull[] = new int[B2_MAX_VERTICES];
    int m = 0;
    int ih = i0;

    while (true) {
        hull[m] = ih;

        int ie = 0;
        for (int j = 1; j < n; ++j) {
            if (ie == ih) {
                ie = j;
                continue;
            }

            Vector2 r = ps[ie].cpy().sub(ps[hull[m]]);
            Vector2 v = ps[j].cpy().sub(ps[hull[m]]);

            float c = r.crs(v);
            if (c < 0.0f) {
                ie = j;
            }

            // Collinearity check
            if (c == 0.0f && v.len2() > r.len2()) {
                ie = j;
            }
        }

        ++m;
        ih = ie;

        if (ie == i0) {
            break;
        }
    }

    if (m < 3) {
        // Polygon is degenerate.
        return true;
    }

    return false;
}

From source file:com.mygdx.entities.DynamicEntities.SteerableEntity.java

private void applySteering() {
    boolean anyAccelerations = false;

    if (!steeringOutput.linear.isZero()) {
        Vector2 force = steeringOutput.linear.scl(MainGame.STEP);
        body.applyForceToCenter(force, true);
        anyAccelerations = true;// www  . j  ava2s  .c o  m
    }

    if (steeringOutput.angular != 0) {
        body.applyTorque(steeringOutput.angular * MainGame.STEP, true);
        anyAccelerations = true;
    } else {
        Vector2 lv = getLinearVelocity();
        if (!lv.isZero()) {
            float o = vectorToAngle(lv);
            body.setAngularVelocity((o - getAngularVelocity()) * MainGame.STEP);
            body.setTransform(body.getPosition(), o);
        }
    }

    if (anyAccelerations) {
        //linear capping
        Vector2 velocity = body.getLinearVelocity();
        float currentSpeedSq = velocity.len2();
        if (currentSpeedSq > maxLinearSpeed * maxLinearSpeed) {
            body.setLinearVelocity(velocity.scl(maxLinearSpeed / (float) Math.sqrt(currentSpeedSq)));
        }

        //angular capping
        if (body.getAngularVelocity() > maxAngularSpeed) {
            body.setAngularVelocity(maxAngularSpeed);
        }
    }
}

From source file:com.mygdx.game.Box2dSteeringEntity.java

License:Apache License

protected void applySteering(SteeringAcceleration<Vector2> steering, float deltaTime) {
    boolean anyAccelerations = false;

    // Update position and linear velocity.
    if (!steeringOutput.linear.isZero()) {
        // this method internally scales the force by deltaTime
        body.applyForceToCenter(steeringOutput.linear, true);
        anyAccelerations = true;/*from   w ww. j  a  v a  2 s .com*/
    }

    // Update orientation and angular velocity
    if (isIndependentFacing()) {
        if (steeringOutput.angular != 0) {
            // this method internally scales the torque by deltaTime
            body.applyTorque(steeringOutput.angular, true);
            anyAccelerations = true;
        }
    } else {
        // If we haven't got any velocity, then we can do nothing.
        Vector2 linVel = getLinearVelocity();
        if (!linVel.isZero(getZeroLinearSpeedThreshold())) {
            float newOrientation = vectorToAngle(linVel);
            body.setAngularVelocity((newOrientation - getAngularVelocity()) * deltaTime); // this is superfluous if independentFacing is always true
            body.setTransform(body.getPosition(), newOrientation);
        }
    }

    if (anyAccelerations) {
        // body.activate();

        // TODO:
        // Looks like truncating speeds here after applying forces doesn't work as expected.
        // We should likely cap speeds form inside an InternalTickCallback, see
        // http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Simulation_Tick_Callbacks

        // Cap the linear speed
        Vector2 velocity = body.getLinearVelocity();
        float currentSpeedSquare = velocity.len2();
        float maxLinearSpeed = getMaxLinearSpeed();
        if (currentSpeedSquare > maxLinearSpeed * maxLinearSpeed) {
            body.setLinearVelocity(velocity.scl(maxLinearSpeed / (float) Math.sqrt(currentSpeedSquare)));
        }

        // Cap the angular speed
        float maxAngVelocity = getMaxAngularSpeed();
        if (body.getAngularVelocity() > maxAngVelocity) {
            body.setAngularVelocity(maxAngVelocity);
        }
    }
}

From source file:de.cubicvoxel.openspacebox.ingame.controller.OsbCamera.java

License:Open Source License

/**
 * Zooms in/out by the given velocity's len2().
 *//*  w w  w.  j  a  va2 s. com*/
private void adjustZoomToVelocity(Vector2 velocity, float deltaTime) {
    float targetZoom = 1 + velocity.len2() * ZOOM_COEFFICIENT * deltaTime;
    float nextZoom = this.zoom;

    // Zoom out faster than zooming in
    if (this.zoom < targetZoom)
        nextZoom = MathUtils.lerp(this.zoom, targetZoom, deltaTime * ZOOM_OUT_SPEED);
    else if (this.zoom > targetZoom)
        nextZoom = MathUtils.lerp(this.zoom, targetZoom, deltaTime * ZOOM_IN_SPEED);

    this.zoom = MathUtils.clamp(nextZoom, MINIMUM_ZOOM, MAXIMUM_ZOOM);
}