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.gmail.emersonmx.asteroids.util.PhysicBodyFactory.java

License:Open Source License

private Vector2[] createSpaceshipShapeVertices() {
    return new Vector2[] { ConverterUtil.pixelToUnit(new Vector2(-16, -8)),
            ConverterUtil.pixelToUnit(new Vector2(16, 0)), ConverterUtil.pixelToUnit(new Vector2(-16, 8)), };
}

From source file:com.greenleaves.mazing.ui.shape.MazeShape.java

License:Apache License

public void init(boolean visible, final Callback<Boolean> callback, final Callback<Exception> exceptionCallback,
        Context ctx) {/*w w  w . jav  a2 s.  c om*/
    setVisible(visible);

    mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);

    new AsyncTask<Void, Void, Boolean>() {
        private Exception mException = null;

        @Override
        public void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        public Boolean doInBackground(final Void... params) {
            Boolean result = true;
            try {
                mMazeGrid = mMazeGenerator.generate(mMazeHeight, mMazeWidth);
                Debug.i("Maze generation completed");
            } catch (final Exception e) {
                mException = e;
                result = false;
            }
            return result;
        }

        @Override
        public void onPostExecute(final Boolean result) {
            if (mException == null) {
                try {
                    Debug.i("Maze drawing start");
                    drawMaze();
                    Debug.i("Maze drawing finish. Add marker");
                    addMarker();
                    Debug.i("Add marker finish. Add target");
                    addTarget();
                    Debug.i("Add target finish");

                    callback.onCallback(result);
                } catch (Exception e) {
                    mException = e;
                }
            }

            if (mException != null) {
                if (exceptionCallback == null) {
                    Debug.e("Error", mException);
                } else {
                    exceptionCallback.onCallback(mException);
                }
            }

            super.onPostExecute(result);
        }
    }.execute((Void[]) null);
}

From source file:com.group6.penguinsgame.DemoMap.java

License:Apache License

@Override
public void create() {
    /**/*from  ww  w.j ava  2s.  c om*/
     * If the viewport's size is not yet known, determine it here.
     */
    if (screenWidth == -1) {
        screenWidth = Gdx.graphics.getWidth();
        screenHeight = Gdx.graphics.getHeight();
    }

    tiledMapHelper = new TiledMapHelper();

    tiledMapHelper = new TiledMapHelper();

    tiledMapHelper.setPackerDirectory("data/packer");

    tiledMapHelper.loadMap("data/world/level1/level.tmx");

    tiledMapHelper.prepareCamera(screenWidth, screenHeight);

    /**
     * Load up the overall texture and chop it in to pieces. In this case,
     * piece.
     */
    overallTexture = new Texture(Gdx.files.internal("data/sprite.png"));
    overallTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    jumperSprite = new Sprite(overallTexture, 0, 0, 31, 37);

    spriteBatch = new SpriteBatch();

    /**
     * You can set the world's gravity in its constructor. Here, the gravity
     * is negative in the y direction (as in, pulling things down).
     */
    // 0. Create a loader for the file saved from the editor.
    // needs work
    BodyEditorLoader loader = new BodyEditorLoader("data/penFig.json");

    world = new World(new Vector2(0.0f, -10.0f), true);

    // 1. Create a BodyDef, as usual.
    BodyDef jumperBodyDef = new BodyDef();//BodyDef bd = new BodyDef();
    jumperBodyDef.type = BodyDef.BodyType.DynamicBody;//bd.type = BodyType.DynamicBody;
    jumperBodyDef.position.set(5.0f, 5.0f);//bd.position.set(0, 0);

    jumper = world.createBody(jumperBodyDef);

    /**
     * Boxes are defined by their "half width" and "half height", hence the
     * 2 multiplier.
     */
    PolygonShape jumperShape = new PolygonShape();
    jumperShape.setAsBox(jumperSprite.getWidth() / (2 * PIXELS_PER_METER),
            jumperSprite.getHeight() / (2 * PIXELS_PER_METER));

    /**
     * The character should not ever spin around on impact.
     */
    jumper.setFixedRotation(true);

    /**
     * The density and friction of the jumper were found experimentally.
     * Play with the numbers and watch how the character moves faster or
     * slower.
     */

    // 2. Create a FixtureDef, as usual.
    FixtureDef jumperFixtureDef = new FixtureDef();//FixtureDef fd = new FixtureDef();
    jumperFixtureDef.shape = jumperShape;
    jumperFixtureDef.density = 0.1f;//fd.density = 1;
    jumperFixtureDef.friction = 2.0f;//fd.friction = 0.5f;
    //fd.restitution = 0.3f;

    // 3. Create a Body, as usual.
    //jumperModel = world.createBody(jumperBodyDef);
    jumper.createFixture(jumperFixtureDef);
    jumperShape.dispose();

    tiledMapHelper.loadCollisions("data/collisions.txt", world, PIXELS_PER_METER);

    // 4. Create the body fixture automatically by using the loader.
    //needs work
    //loader.attachFixture(jumperModel, "test01", jumperFixtureDef, JUMPER_WIDTH);
    //jumperModelOrigin = loader.getOrigin("test01", JUMPER_WIDTH).cpy();

    debugRenderer = new Box2DDebugRenderer();

    lastRender = System.nanoTime();
}

From source file:com.group6.penguinsgame.DemoMap.java

License:Apache License

@Override
public void render() {
    long now = System.nanoTime();
    //Vector2 bottlePos = jumperModel.getPosition().sub(jumperModelOrigin);

    /**//from  w  ww  . j ava 2  s  .c o  m
     * Detect requested motion.
     */
    boolean moveLeft = false;
    boolean moveRight = false;
    boolean doJump = false;

    if (Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT)) {
        moveRight = true;
    } else {
        for (int i = 0; i < 2; i++) {
            if (Gdx.input.isTouched(i) && Gdx.input.getX() > Gdx.graphics.getWidth() * 0.80f) {
                moveRight = true;
            }
        }
    }

    if (Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT)) {
        moveLeft = true;
    } else {
        for (int i = 0; i < 2; i++) {
            if (Gdx.input.isTouched(i) && Gdx.input.getX() < Gdx.graphics.getWidth() * 0.20f) {
                moveLeft = true;
            }
        }
    }

    if (Gdx.input.isKeyPressed(Input.Keys.DPAD_UP)) {
        doJump = true;
    } else {
        for (int i = 0; i < 2; i++) {
            if (Gdx.input.isTouched(i) && Gdx.input.getY() < Gdx.graphics.getHeight() * 0.20f) {
                doJump = true;
            }
        }
    }

    /**
     * Act on that requested motion.
     * 
     * This code changes the jumper's direction. It's handled separately
     * from the jumping so that the player can jump and move simultaneously.
     * The horizontal figure was arrived at experimentally -- try other
     * values to experience different speeds.
     * 
     * The impulses are applied to the center of the jumper.
     */
    if (moveRight) {
        jumper.applyLinearImpulse(new Vector2(0.05f, 0.0f), jumper.getWorldCenter());
        if (jumperFacingRight == false) {
            jumperSprite.flip(true, false);
        }
        jumperFacingRight = true;
    } else if (moveLeft) {
        jumper.applyLinearImpulse(new Vector2(-0.05f, 0.0f), jumper.getWorldCenter());
        if (jumperFacingRight == true) {
            jumperSprite.flip(true, false);
        }
        jumperFacingRight = false;
    }

    /**
     * The jumper dude can only jump while on the ground. There are better
     * ways to detect ground contact, but for our purposes it is sufficient
     * to test that the vertical velocity is zero (or close to it). As in
     * the above code, the vertical figure here was found through
     * experimentation. It's enough to get the guy off the ground.
     * 
     * As before, impulse is applied to the center of the jumper.
     */
    if (doJump && Math.abs(jumper.getLinearVelocity().y) < 1e-9) {
        jumper.applyLinearImpulse(new Vector2(0.0f, 0.8f), jumper.getWorldCenter());
    }

    /**
     * Have box2d update the positions and velocities (and etc) of all
     * tracked objects. The second and third argument specify the number of
     * iterations of velocity and position tests to perform -- higher is
     * more accurate but is also slower.
     */
    world.step(Gdx.app.getGraphics().getDeltaTime(), 3, 3);

    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    /**
     * A nice(?), blue backdrop.
     */
    Gdx.gl.glClearColor(0, 0.5f, 0.9f, 0);

    /**
     * The camera is now controlled primarily by the position of the main
     * character, and secondarily by the map boundaries.
     */

    tiledMapHelper.getCamera().position.x = PIXELS_PER_METER * jumper.getPosition().x;

    /**
     * Ensure that the camera is only showing the map, nothing outside.
     */
    if (tiledMapHelper.getCamera().position.x < Gdx.graphics.getWidth() / 2) {
        tiledMapHelper.getCamera().position.x = Gdx.graphics.getWidth() / 2;
    }
    if (tiledMapHelper.getCamera().position.x >= tiledMapHelper.getWidth() - Gdx.graphics.getWidth() / 2) {
        tiledMapHelper.getCamera().position.x = tiledMapHelper.getWidth() - Gdx.graphics.getWidth() / 2;
    }

    if (tiledMapHelper.getCamera().position.y < Gdx.graphics.getHeight() / 2) {
        tiledMapHelper.getCamera().position.y = Gdx.graphics.getHeight() / 2;
    }
    if (tiledMapHelper.getCamera().position.y >= tiledMapHelper.getHeight() - Gdx.graphics.getHeight() / 2) {
        tiledMapHelper.getCamera().position.y = tiledMapHelper.getHeight() - Gdx.graphics.getHeight() / 2;
    }

    tiledMapHelper.getCamera().update();
    tiledMapHelper.render();

    /**
     * Prepare the SpriteBatch for drawing.
     */
    spriteBatch.setProjectionMatrix(tiledMapHelper.getCamera().combined);
    spriteBatch.begin();

    jumperSprite.setPosition(PIXELS_PER_METER * jumper.getPosition().x - jumperSprite.getWidth() / 2,
            PIXELS_PER_METER * jumper.getPosition().y - jumperSprite.getHeight() / 2);
    jumperSprite.draw(spriteBatch);

    /**
     * "Flush" the sprites to screen.
     */
    spriteBatch.end();

    /**
     * Draw this last, so we can see the collision boundaries on top of the
     * sprites and map.
     */
    debugRenderer.render(world, tiledMapHelper.getCamera().combined.scale(DemoMap.PIXELS_PER_METER,
            DemoMap.PIXELS_PER_METER, DemoMap.PIXELS_PER_METER));

    now = System.nanoTime();
    if (now - lastRender < 30000000) { // 30 ms, ~33FPS
        try {
            Thread.sleep(30 - (now - lastRender) / 1000000);
        } catch (InterruptedException e) {
        }
    }

    lastRender = now;
}

From source file:com.group6.penguinsgame.Penguins.java

License:Apache License

@Override
public void create() {
    /**//from w  w w.j a  va2  s.c o m
     * If the viewport's size is not yet known, determine it here.
     */
    if (screenWidth == -1) {
        screenWidth = Gdx.graphics.getWidth();
        screenHeight = Gdx.graphics.getHeight();
    }

    tiledMapHelper = new TiledMapHelper();

    tiledMapHelper.setPackerDirectory("data/packer");

    tiledMapHelper.loadMap("data/world/level1/level.tmx");

    tiledMapHelper.prepareCamera(screenWidth, screenHeight);

    world = new World(new Vector2(0.0f, -10.0f), true);

    tiledMapHelper.loadCollisions("data/collisions.txt", world, PIXELS_PER_METER);

    debugRenderer = new Box2DDebugRenderer();

    lastRender = System.nanoTime();
}

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

License:Apache License

public void loadWorld(int worldNumber) {
    try {//from  w ww. j a  v  a2 s .  c o m
        XmlReader reader = new XmlReader();
        Element file = reader.parse(Gdx.files.internal("data/world" + worldNumber + ".xml"));
        Element level_definition = file.getChildByName("level_definition");

        startFuelAmmount = Integer.parseInt(level_definition.get("player_fuel_ammount"));
        canonsFireInterval = Float.parseFloat(level_definition.get("canons_fire_interval"));
        float gravityX = Float.parseFloat(level_definition.get("gravity_x"));
        float gravityY = Float.parseFloat(level_definition.get("gravity_y"));
        String terrainFileName = level_definition.get("terrain_file");

        box2dWorld = new World(new Vector2(gravityX, gravityY), true);
        terrain = new Terrain(box2dWorld, "data/" + terrainFileName);

        landingZones = new ArrayList<LandingZone>();
        canons = new ArrayList<Canon>();
        bullets = new ArrayList<Bullet>();
        blackHoles = new ArrayList<BlackHole>();
        stars = new ArrayList<Star>();
        objectsToDestroy = new ArrayList<GameObject>();

        Element objects = file.getChildByName("objects");
        Iterator<Element> iterator_objects = objects.getChildrenByName("object").iterator();
        while (iterator_objects.hasNext()) {
            Element object_element = (Element) iterator_objects.next();
            String type = object_element.get("type");
            float x = Float.parseFloat(object_element.get("x"));
            float y = Float.parseFloat(object_element.get("y"));

            if (type.equals("Canon")) {
                float rotation = Float.parseFloat(object_element.get("rotation"));
                canons.add(new Canon(box2dWorld, x, y, rotation));
            } else if (type.equals("BlackHole")) {
                int strength = Integer.parseInt(object_element.get("strength"));
                blackHoles.add(new BlackHole(box2dWorld, x, y, strength));
            } else if (type.equals("LandingZone")) {
                float rotation = Float.parseFloat(object_element.get("rotation"));
                String subtype = object_element.getAttribute("subtype");
                if (subtype.equals("Start"))
                    landingZones.add(new LandingZone(1, box2dWorld, x, y, rotation));
                else if (subtype.equals("Finish"))
                    landingZones.add(new LandingZone(2, box2dWorld, x, y, rotation));
                else
                    landingZones.add(new LandingZone(3, box2dWorld, x, y, rotation));
            } else if (type.equals("Star")) {
                stars.add(new Star(box2dWorld, x, y));
            }
        }
        numOfStars = stars.size();
        player = new Player(box2dWorld, 0, 0, startFuelAmmount);
        contactListener = new CollisionProcessor(this);
        box2dWorld.setContactListener(contactListener);
    } catch (Exception e) {
        System.out.println(e);
    }
}

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

License:Apache License

public ScrollingBackground(OrthographicCamera camera, Texture texture, SpriteBatch batch) {
    if (texture.getWidth() == 256) {
        this.tilesCountX = 6;
        this.tilesCountY = 4;
    }//from ww w.java2 s  .c  o m
    if (texture.getWidth() == 512) {
        this.tilesCountX = 5;
        this.tilesCountY = 4;
    }
    this.textureRegion = new TextureRegion(texture);
    this.batch = batch;
    this.textureCoords = new Vector2[tilesCountX * tilesCountY];
    this.camera = camera;
    this.textureWidth = texture.getWidth();
    this.x = camera.frustum.planePoints[0].x;
    this.y = camera.frustum.planePoints[0].y;
    int index = 0;
    for (int i = 0; i < tilesCountY; i++) {
        for (int j = 0; j < tilesCountX; j++) {
            textureCoords[index] = new Vector2(x + (j * textureWidth), y + (i * textureWidth));
            index++;
        }
    }
}

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

License:Apache License

public ScrollingBackground(OrthographicCamera camera, TextureRegion textureRegion, SpriteBatch batch) {
    if (textureRegion.getRegionWidth() == 256) {
        this.tilesCountX = 6;
        this.tilesCountY = 4;
    }//  w ww  .j a v  a 2  s.co  m
    if (textureRegion.getRegionWidth() == 512) {
        this.tilesCountX = 5;
        this.tilesCountY = 4;
    }
    this.textureRegion = textureRegion;
    this.batch = batch;
    this.textureCoords = new Vector2[tilesCountX * tilesCountY];
    this.camera = camera;
    this.textureWidth = textureRegion.getRegionWidth();
    this.x = camera.frustum.planePoints[0].x;
    this.y = camera.frustum.planePoints[0].y;
    int index = 0;
    for (int i = 0; i < tilesCountY; i++) {
        for (int j = 0; j < tilesCountX; j++) {
            textureCoords[index] = new Vector2(x + (j * textureWidth), y + (i * textureWidth));
            index++;
        }
    }
}

From source file:com.hatstick.fireman.physics.Box2DPhysicsWorld.java

License:Apache License

public void createPhysicsWorld() {

    xEngine = new ExplosionEngine();

    // create the debug renderer
    renderer = new Box2DDebugRenderer();

    // create the world
    world = new World(new Vector2(0, -3), true);

    bob.setBody(createPhysicsObject(bob.getBounds(), ModelType.PLAYER, -1).getBody());

    // Create our enemy's physical representations
    for (Map.Entry<Civilian, Integer> civilian : level.getEnemies().entrySet()) {
        civilian.getKey().setFixture(/*from w w w.j  a v a2 s  . c  o m*/
                createPhysicsObject(civilian.getKey().getBounds(), ModelType.ENEMY, civilian.getValue()));
    }

    // Create our item's physical representations
    for (Map.Entry<Item, Integer> item : level.getItems().entrySet()) {
        item.getKey()
                .setFixture(createPhysicsObject(item.getKey().getBounds(), ModelType.ITEM, item.getValue()));
    }

    // Create our level out of blocks
    for (Block block : level.getBlocks()) {
        createBoxes(block.getBounds());
    }

    //   createDestruction();

    world.setContactListener(new ContactListener() {
        @Override
        public void beginContact(Contact contact) {

            // Get our UserData object, and check for contacts
            UserData dataA = (UserData) contact.getFixtureA().getUserData();
            UserData dataB = (UserData) contact.getFixtureA().getUserData();

            /** Used for determining if character can jump or not **/
            if (dataA.modelType == ModelType.FOOT_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(1);
                    bob.canJump(true);
                }
            }
            if (dataB.modelType == ModelType.FOOT_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(1);
                }
            }

            if (dataA.modelType == ModelType.LEFT_SIDE_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumLeftSideContacts(1);
                    bob.canJump(true);
                }
            }
            if (dataB.modelType == ModelType.LEFT_SIDE_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumLeftSideContacts(1);
                }
            }

            if (dataA.modelType == ModelType.RIGHT_SIDE_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumRightSideContacts(1);
                    bob.canJump(true);
                }
            }
            if (dataB.modelType == ModelType.RIGHT_SIDE_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumRightSideContacts(1);
                }
            }

            /** Touching an item (used for picking up items) **/
            if (dataA.modelType == ModelType.PLAYER && dataB.modelType == ModelType.ITEM
                    || dataB.modelType == ModelType.ITEM && dataA.modelType == ModelType.PLAYER) {

                MouseJointDef def = new MouseJointDef();
                def.bodyA = contact.getFixtureA().getBody();
                def.bodyB = contact.getFixtureB().getBody();
                dataA = (UserData) def.bodyA.getUserData();
                def.collideConnected = false;
                def.target.set(testPoint.x, testPoint.y);

                if (dataA.modelType == ModelType.PLAYER) {
                    def.target.set(def.bodyA.getWorldCenter());
                    def.maxForce = 1000.0f * def.bodyA.getMass();
                } else {
                    def.target.set(def.bodyB.getWorldCenter());
                    def.maxForce = 1000.0f * def.bodyB.getMass();
                }
                jointsToCreate.add(def);
            }
        }

        @Override
        public void endContact(Contact contact) {
            // Get our UserData object, and check for contacts
            UserData dataA = (UserData) contact.getFixtureA().getUserData();
            UserData dataB = (UserData) contact.getFixtureA().getUserData();

            /** Used for determining if character can jump or not **/
            if (dataA.modelType == ModelType.FOOT_SENSOR) {
                if (dataA.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(-1);
                }
            }
            if (dataB.modelType == ModelType.FOOT_SENSOR) {
                if (dataB.parentId == -1) { // PlayerCharacter's foot
                    bob.setNumFootContacts(-1);
                }
            }
        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
        }
    });
}

From source file:com.hatstick.fireman.physics.Box2DPhysicsWorld.java

License:Apache License

private Fixture createPhysicsObject(Rectangle bounds, ModelType type, Integer id) {

    UserData userData = new UserData(numEnterPoints, type, null);
    CircleShape objectPoly = new CircleShape();
    objectPoly.setRadius(bounds.width / 2);

    BodyDef enemyBodyDef = new BodyDef();
    enemyBodyDef.type = BodyType.DynamicBody;
    enemyBodyDef.position.x = bounds.x;/*from   w ww  .j  a va2 s .c o m*/
    enemyBodyDef.position.y = bounds.y;
    Body objectBody = world.createBody(enemyBodyDef);
    FixtureDef objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = objectPoly;

    //   objectBody.setUserData(userData);
    objectFixtureDef.restitution = .025f;
    Fixture fixture = objectBody.createFixture(objectFixtureDef);
    fixture.setUserData(userData);
    objectBody.setLinearDamping(2f);
    objectBody.setGravityScale(.4f);
    objectBody.setFixedRotation(true);
    objectPoly.dispose();
    numEnterPoints++;

    //add a sensor on the bottom to check if touching ground (for jumping)
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(bounds.width / 3, bounds.height / 8, new Vector2(0, -bounds.height / 2), 0);
    objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = polygonShape;
    objectFixtureDef.isSensor = true;
    Fixture footSensorFixture = objectBody.createFixture(objectFixtureDef);
    footSensorFixture.setUserData(new UserData(numEnterPoints, ModelType.FOOT_SENSOR, id));

    //add a sensor on left side to check if touching wall (for grappling)
    PolygonShape polygonShape2 = new PolygonShape();
    polygonShape2.setAsBox(bounds.width / 8, bounds.height / 3, new Vector2(-bounds.width / 2, 0), 0);
    objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = polygonShape2;
    objectFixtureDef.isSensor = true;
    Fixture leftSideSensorFixture = objectBody.createFixture(objectFixtureDef);
    leftSideSensorFixture.setUserData(new UserData(numEnterPoints, ModelType.LEFT_SIDE_SENSOR, id));

    //add a sensor on right side to check if touching wall (for grappling)
    polygonShape2.setAsBox(bounds.width / 8, bounds.height / 3, new Vector2(bounds.width / 2, 0), 0);
    objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = polygonShape2;
    objectFixtureDef.isSensor = true;
    Fixture rightSideSensorFixture = objectBody.createFixture(objectFixtureDef);
    rightSideSensorFixture.setUserData(new UserData(numEnterPoints, ModelType.RIGHT_SIDE_SENSOR, id));

    return fixture;
}