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

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

Introduction

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

Prototype

public Vector2(float x, float y) 

Source Link

Document

Constructs a vector with the given components

Usage

From source file:com.laex.cg2d.model.descs.Vec2PropertySource.java

License:Open Source License

@Override
public Object getEditableValue() {
    return new Vector2(this.vec2.x, this.vec2.y);
}

From source file:com.laex.cg2d.model.joints.BEPrismaticJoint.java

License:Open Source License

@Override
public void computeLocalAnchors(int ptmRatio) {
    getLocalAnchorA().x = (getSource().getBounds().width / ptmRatio) / 2;
    getLocalAnchorA().y = (getSource().getBounds().height / ptmRatio) / 2;

    getLocalAnchorB().x = getLocalAnchorA().x;
    getLocalAnchorB().y = getLocalAnchorA().y;

    /* Compute world anchor for prismastic joint */
    Vector2 a1 = new Vector2(getSource().getBounds().x, getSource().getBounds().y);
    Vector2 a2 = new Vector2(getTarget().getBounds().x, getTarget().getBounds().y);

    Vector2 avg = a1.add(a2).div(2).div(ptmRatio);

    getWorldAnchor().x = avg.x;/*from   w w  w .j a  va  2  s . com*/
    getWorldAnchor().y = avg.y;
}

From source file:com.laex.cg2d.model.joints.BEPulleyJoint.java

License:Open Source License

/**
 * Instantiates a new bE pulley joint./* www . j  a  v  a  2s  .  c om*/
 * 
 * @param source
 *          the source
 * @param target
 *          the target
 */
public BEPulleyJoint(Shape source, Shape target) {
    super(source, target);

    groundAnchorA = new Vector2(-1, 1);
    groundAnchorB = new Vector2(1, 1);
    ratio = 1;
}

From source file:com.laex.cg2d.render.impl.BackgroundManager.java

License:Open Source License

@Override
public void create() {
    backgroundTextures = new LinkedList<Sprite>();
    for (CGLayer layer : manipulator.model().getLayersList()) {
        for (CGShape shape : layer.getShapeList()) {

            if (!(shape.getEditorShapeType() == CGEditorShapeType.BACKGROUND_SHAPE)) {
                continue;
            }/*from   w  ww .  j  a va 2s .  c o  m*/

            FileHandle handle = Gdx.files.absolute(shape.getBackgroundResourceFile().getResourceFileAbsolute());

            Texture tex = new Texture(handle);
            tex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
            /* for clamping edge of background textures */
            tex.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);

            Sprite sprite = new Sprite(tex);

            float x = shape.getBounds().getX();
            float y = shape.getBounds().getY();
            float width = shape.getBounds().getWidth();
            float height = shape.getBounds().getHeight();

            Vector2 scrPos = new Vector2(x, y);
            Vector2 worldPos = ScreenToWorld.inst(manipulator.model()).screenToWorldFlipped(scrPos, height);
            sprite.setPosition(worldPos.x, worldPos.y);

            float w = (width / manipulator.ptmRatio());
            float h = (height / manipulator.ptmRatio());

            sprite.setSize(w, h);

            backgroundTextures.add(sprite);
        }
    }
}

From source file:com.laex.cg2d.render.impl.EntityManager.java

License:Open Source License

/**
 * Creates the entity./* w  ww .j  a  v  a  2  s. co m*/
 * 
 * @param shape
 *          the shape
 * @param animationName
 *          the animation name
 * @return the body
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public Body createEntity(CGShape shape, String animationName) throws IOException {
    CGEditorShapeType eType = shape.getEditorShapeType();

    if (eType == CGEditorShapeType.BACKGROUND_SHAPE) {
        return null;
    }

    /* We alo create shapes */
    if (eType == CGEditorShapeType.SIMPLE_SHAPE_BOX || eType == CGEditorShapeType.SIMPLE_SHAPE_CIRCLE
            || eType == CGEditorShapeType.SIMPLE_SHAPE_HEDGE || eType == CGEditorShapeType.SIMPLE_SHAPE_VEDGE) {
        Body b = manipulator.createBody(shape, null, null);
        b.setUserData(shape);
        return b;
    }

    /* For Entities */
    String entPath = shape.getEntityRefFile().getResourceFileAbsolute();
    final CGEntity entity = CGEntity.parseFrom(Gdx.files.absolute(entPath).read());

    shapeToEntityMap.put(shape, entity);

    /* Entity Animation */
    CGEntityAnimation ea = null;

    /* If name is not provided, get default animation */
    if (animationName == null) {
        ea = RunnerUtil.getDefaultAnimation(entity);
    } else {
        ea = RunnerUtil.getAnimationFrom(entity, animationName);
    }

    Body b = manipulator.createBody(shape, entity, ea);
    b.setUserData(shape);

    // Resource file empty indicates this entity might not have
    // image & collision shape defined.
    if (ea.getSpritesheetFile().getResourceFileAbsolute().trim().isEmpty()) {
        manipulator.world().destroyBody(b);
        return null;
    }

    FileHandle handle = Gdx.files.absolute(ea.getSpritesheetFile().getResourceFileAbsolute());

    Texture tex = new Texture(handle);
    tex.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    Array<TextureRegion> walkFrames = new Array<TextureRegion>();

    for (CGEntitySpritesheetItem cgEi : ea.getSpritesheetItemsList()) {
        CGBounds bnds = cgEi.getExtractBounds();
        TextureRegion tr = new TextureRegion(tex, (int) bnds.getX(), (int) bnds.getY(), (int) bnds.getWidth(),
                (int) bnds.getHeight());
        walkFrames.add(tr);
    }

    Animation spriteAnimation = new Animation(ea.getAnimationDuration(), walkFrames);
    shapeToAnimationMap.put(shape, spriteAnimation);

    Sprite spr = new Sprite(spriteAnimation.getKeyFrame(stateTime, true));

    // Set the position & size
    float x = shape.getBounds().getX();
    float y = shape.getBounds().getY();
    float width = shape.getBounds().getWidth();
    float height = shape.getBounds().getHeight();

    Vector2 scrPos = new Vector2(x, y);
    Vector2 worldPos = ScreenToWorld.inst(manipulator.model()).screenToWorldFlipped(scrPos, height);
    spr.setPosition(worldPos.x, worldPos.y);

    // the position circle (collision shape) will vary with that of
    // a box. so
    // we need to check and set position for each types
    if (ea.getCollisionType() == CGEntityCollisionType.CIRCLE) {
        Vector3 origin = shapeToAnimationOriginMap.get(shape);

        float radius = origin.z;

        float x1 = (worldPos.x - radius);
        float y1 = (worldPos.y - radius);
        spr.setPosition(x1, y1);
    }

    float w = ((float) width / manipulator.ptmRatio());
    float h = ((float) height / manipulator.ptmRatio());

    spr.setSize(w, h);

    shapeToSpriteMap.put(shape, spr);

    return b;
}

From source file:com.laex.cg2d.render.impl.EntityManager.java

License:Open Source License

public Vector2[] normalizeVertices(List<CGVector2> vertices, float height) {
    Vector2[] vss = new Vector2[vertices.size()];

    for (int i = 0; i < vertices.size(); i++) {
        CGVector2 vi = vertices.get(i);//w w  w  .j a v a  2 s. c  o  m
        Vector2 v = new Vector2(vi.getX(), vi.getY());
        v.y = height - v.y;
        vss[i] = ScreenToWorld.inst(manipulator.model()).screenToWorld(v);
    }

    // after flipping, reverse the vertices
    Vector2[] inverse = new Vector2[vertices.size()];
    int len = vertices.size() - 1;
    for (int i = 0; i < vertices.size(); i++) {
        inverse[i] = vss[len--];
    }

    return inverse;
}

From source file:com.laex.cg2d.render.impl.EntityManager.java

License:Open Source License

/**
 * Creates the entity collision shape.//from   ww  w  .  j  a v a2s .c om
 * 
 * @param shape
 *          the shape
 * @param entity
 *          the entity
 * @param ea
 *          the ea
 * @param bodyDef
 *          the body def
 * @param fixDef
 *          the fix def
 * @param b
 *          the b
 */
public void createEntityCollisionShape(CGShape shape, CGEntity entity, CGEntityAnimation ea, BodyDef bodyDef,
        FixtureDef fixDef, Body b) {

    CGEntityCollisionType shapeType = ea.getCollisionType();
    PolygonShape polyShape = new PolygonShape();
    Vector2[] va = null;

    // check if shape type is NONE. NONE shape type means that this entity
    // has no collision parameters defined.
    // We simple ignore this and do not create any shape collision for this
    // object
    if (shapeType == CGEntityCollisionType.NONE) {
        // /set empty origin vertex so that other codes do not have to check null
        // pointer exception on its part
        shapeToAnimationOriginMap.put(shape, new Vector3(0, 0, 0));
        return;
    }

    switch (shapeType) {
    case BOX:
        va = normalizeVertices(ea.getVerticesList(), shape.getBounds().getHeight());
        polyShape.set(va);

        shapeToAnimationOriginMap.put(shape, new Vector3(0, 0, 0));

        fixDef.shape = polyShape;
        b.createFixture(fixDef);
        break;

    case CIRCLE: {
        manipulator.world().destroyBody(b);

        CircleShape circShape = new CircleShape();

        /* Decode x,y, width, height of collision shape from the vertices */
        CGVector2 v1 = ea.getVertices(0);
        CGVector2 v2 = ea.getVertices(2);

        Rectangle r = new Rectangle(v1.getX(), v1.getY(), v2.getX(), v2.getY());
        r.width = r.width - r.x;
        r.height = r.height - r.y;

        // this radius is calculated for circle's collision shape data not
        // the sprite width/height data
        float radius = CircleBody.calculateRadiusOfCircleShape(r.width, manipulator.ptmRatio());

        Vector2 cpos = new Vector2(r.x, r.y);
        cpos.y = shape.getBounds().getHeight() - r.height - r.y;
        cpos = ScreenToWorld.inst(manipulator.model()).screenToWorld(cpos);

        /* Calculate origin */
        int x = (int) r.x;
        int y = (int) r.y;
        int w = (int) r.width;
        int h = (int) r.height;

        /*
         * ptmRatioSquared should be casted to integer to avoid floating point
         * calculation division. If not, the orirgin will actully diverge and will
         * be clearly seen in the rotation of the circle shape
         */
        int ptmRatioSquared = (int) (manipulator.ptmRatio() * manipulator.ptmRatio());
        float ox = (x + w) / (ptmRatioSquared) + radius;
        float oy = (y + h) / (ptmRatioSquared) + radius;
        /* End origin calculatio */

        b = manipulator.world().createBody(bodyDef);

        circShape.setRadius(radius);
        circShape.setPosition(cpos);

        shapeToAnimationOriginMap.put(shape, new Vector3(ox, oy, radius));

        fixDef.shape = circShape;
        b.createFixture(fixDef);
    }
        break;

    case CUSTOM:
        BodyEditorLoader bel = new BodyEditorLoader(
                Gdx.files.absolute(ea.getFixtureFile().getResourceFileAbsolute()));
        // scale = image width or image height / ptmRatio
        /*
         * bodyScale: Consider this: scale is a factor which scales the vertices
         * created by Physcis Editor. This scale is not equals to ptmRatio or
         * scaleFactor. bodyScale is the width or height of the image / ptmRatio
         * imageWidth = 32, scale = imageWidth / ptmRatio = 32 / 16 = 2 imageWidth
         * = 32, scale = imageWidth / ptmRatio = 32 / 32 = 1
         */
        float bodyScale = (shape.getBounds().getWidth() / manipulator.ptmRatio());
        bel.attachFixture(b, ea.getAnimationName(), fixDef, bodyScale);
        Vector2 or = bel.getOrigin(ea.getAnimationName(), bodyScale);
        shapeToAnimationOriginMap.put(shape, new Vector3(or.x, or.y, 0));
        break;

    case NONE:
    default:
        break;
    }

}

From source file:com.laex.cg2d.render.impl.ScreenManagerImpl.java

License:Open Source License

@Override
public Vector2 newVector(float x, float y) {
    return new Vector2(x, y);
}

From source file:com.laex.cg2d.render.MyGdxGame.java

License:Open Source License

@Override
public void create() {
    model = loadGameModel();//from  www  . j  a v  a2 s. c  o m

    gravityX = model.getScreenPrefs().getWorldPrefs().getGravityX();
    gravityY = model.getScreenPrefs().getWorldPrefs().getGravityY();
    timeStep = model.getScreenPrefs().getWorldPrefs().getTimeStep();
    velocityIterations = model.getScreenPrefs().getWorldPrefs().getVelocityIterations();
    positionIterations = model.getScreenPrefs().getWorldPrefs().getPositionIterations();

    bgColor = new Vector3();
    bgColor.set(model.getScreenPrefs().getBackgroundColor().getR(),
            model.getScreenPrefs().getBackgroundColor().getG(),
            model.getScreenPrefs().getBackgroundColor().getB());
    bgColor.div(255); /* convert to the floating point color */

    Texture.setEnforcePotImages(false);

    // models init
    world = new World(new Vector2(gravityX, gravityY), true);

    // render init
    batch = new SpriteBatch();
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    int ptmRatio = model.getScreenPrefs().getWorldPrefs().getPtmRatio();

    camera = new OrthographicCamera(w / ptmRatio, h / ptmRatio);
    camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);

    screenManager = new ScreenManagerImpl(model, world, camera, batch);
    mouseJointManager = new MouseJointManager(screenManager);
    luaScriptManager = new LuaScriptManager(screenManager, screenControllerFileLua);
    collisionDetectionMgr = new CollisionDetectionManager(screenManager, luaScriptManager);
    fpsCalculator = new FPSCalculator();

    try {

        screenManager.create();
        mouseJointManager.create();
        luaScriptManager.create();
        collisionDetectionMgr.create();
        fpsCalculator.create();

    } catch (Throwable t) {
        AppExceptionUtil.handle(t);
    }

    Gdx.input.setInputProcessor(mouseJointManager);

    // invoke fps update initially
    fpsCalculator.render();
}

From source file:com.laex.cg2d.render.util.ProtoBufTypeConversionUtil.java

License:Open Source License

/**
 * As vector2./*from  www .  j  a  va2 s .  com*/
 * 
 * @param vec
 *          the vec
 * @return the vector2
 */
public static Vector2 asVector2(CGVector2 vec) {
    return new Vector2(vec.getX(), vec.getY());
}