Java Code Examples for com.badlogic.gdx.math.Vector2

The following examples show how to use com.badlogic.gdx.math.Vector2. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override public IFuture<Void> visualize(PoisonShotResult result) {
    final Future<Void> future = new Future<Void>();
    final WorldObjectView actorView = visualizer.viewController.getView(result.creature);
    WorldObjectView targetView = visualizer.viewController.getView(result.target);
    Vector2 direction = tmp.set(result.target.getX(), result.target.getY()).sub(result.creature.getX(), result.creature.getY());

    visualizer.viewController.scroller.centerOn(result.target);
    float dx = targetView.getX() - actorView.getX();
    float dy = targetView.getY() - actorView.getY();

    final ImageSubView arrow = new ImageSubView("animation/poison-dart");
    arrow.getActor().setOrigin(13, 14);
    arrow.getActor().setRotation(direction.angle());
    arrow.getActor().addAction(Actions.sequence(
        Actions.moveBy(dx, dy, tmp.set(dx, dy).len() * 0.003f),
        Actions.run(new Runnable() {
            @Override public void run() {
                SoundManager.instance.playSound("arrow-shot");
                actorView.removeSubView(arrow);
                future.happen();
            }
        })
    ));
    actorView.addSubView(arrow);
    return future;
}
 
Example 2
Source Project: ud406   Source File: LevelLoader.java    License: MIT License 6 votes vote down vote up
private static void loadNonPlatformEntities(Level level, JSONArray nonPlatformObjects) {
    for (Object o : nonPlatformObjects) {
        JSONObject item = (JSONObject) o;

        final Vector2 imagePosition = extractXY(item);

        if (item.get(Constants.LEVEL_IMAGENAME_KEY).equals(Constants.POWERUP_SPRITE)) {
            final Vector2 powerupPosition = imagePosition.add(Constants.POWERUP_CENTER);
            Gdx.app.log(TAG, "Loaded a powerup at " + powerupPosition);
            level.getPowerups().add(new Powerup(powerupPosition));
        } else if (item.get(Constants.LEVEL_IMAGENAME_KEY).equals(Constants.STANDING_RIGHT)) {
            final Vector2 gigaGalPosition = imagePosition.add(Constants.GIGAGAL_EYE_POSITION);
            Gdx.app.log(TAG, "Loaded GigaGal at " + gigaGalPosition);
            level.setGigaGal(new GigaGal(gigaGalPosition, level));
        } else if (item.get(Constants.LEVEL_IMAGENAME_KEY).equals(Constants.EXIT_PORTAL_SPRITE_1)) {
            final Vector2 exitPortalPosition = imagePosition.add(Constants.EXIT_PORTAL_CENTER);
            Gdx.app.log(TAG, "Loaded the exit portal at " + exitPortalPosition);
            level.setExitPortal(new ExitPortal(exitPortalPosition));
        }

    }
}
 
Example 3
Source Project: libgdx-demo-pax-britannica   Source File: Debris.java    License: MIT License 6 votes vote down vote up
public Debris(Vector2 position) {
	super();
	this.position = position;
	this.setPosition(position.x, position.y);

	this.facing.rotate(random_direction);
	this.setScale(random_scale, random_scale);

	switch (MathUtils.random(0, 2)) {
	case 0:
		this.set(Resources.getInstance().debrisSmall);
		break;
	case 1:
		this.set(Resources.getInstance().debrisMed);
		break;
	default:
		this.set(Resources.getInstance().debrisLarge);
		break;
	}
}
 
Example 4
Source Project: ud405   Source File: Icicles.java    License: MIT License 6 votes vote down vote up
public void update(float delta) {
    if (MathUtils.random() < delta * difficulty.spawnRate) {
        Vector2 newIciclePosition = new Vector2(
                MathUtils.random() * viewport.getWorldWidth(),
                viewport.getWorldHeight()
        );
        Icicle newIcicle = new Icicle(newIciclePosition);
        icicleList.add(newIcicle);
    }

    for (Icicle icicle : icicleList) {
        icicle.update(delta);
    }

    icicleList.begin();
    for (int i = 0; i < icicleList.size; i++) {
        if (icicleList.get(i).position.y < -Constants.ICICLES_HEIGHT) {
            iciclesDodged += 1;
            icicleList.removeIndex(i);
        }
    }
    icicleList.end();
}
 
Example 5
Source Project: Unlucky   Source File: Util.java    License: MIT License 6 votes vote down vote up
/**
 * Returns an instance of an Entity based on numerical Entity id
 *
 * @param id
 * @param position
 * @param map
 * @param rm
 * @return
 */
public static Entity getEntity(int id, Vector2 position, TileMap map, ResourceManager rm) {
    switch (id) {
        case 2: return new Normal("slime", position, map, rm, 1, 0, 2, 1 / 3f);
        case 3: return new Normal("blue slime", position, map, rm, 1, 2, 2, 1 / 3f);
        case 4: return new Normal("blast slime", position, map, rm, 1, 4, 2, 1 / 3f);
        case 5: return new Boss("slime king", 0, position, map, rm, 1, 6, 2, 1 / 3f);
        case 6: return new Normal("ghost", position, map, rm, 2, 0, 2, 1 / 3f);
        case 7: return new Normal("zombie", position, map, rm, 2, 2, 2, 1 / 3f);
        case 8: return new Normal("skeleton", position, map, rm, 2, 4, 2, 1 / 3f);
        case 9: return new Normal("witch", position, map, rm, 2, 6, 2, 1 / 3f);
        case 10: return new Boss("red reaper", 1, position, map, rm, 2, 8, 2, 1 / 3f);
        case 11: return new Normal("snow puff", position, map, rm, 3, 0, 2, 1 / 3f);
        case 12: return new Normal("angry penguin", position, map, rm, 3, 2, 2, 1 / 3f);
        case 13: return new Normal("yeti", position, map, rm, 3, 4, 2, 1 / 3f);
        case 14: return new Normal("ice bat", position, map, rm, 3, 6, 2, 1 / 3f);
        case 15: return new Boss("ice golem", 2, position, map, rm, 3, 8, 2, 1 / 3f);
    }
    return null;
}
 
Example 6
Source Project: Bomberman_libGdx   Source File: PlayerSystem.java    License: MIT License 6 votes vote down vote up
protected boolean hitBombHorizontal(final Body body, Vector2 fromV, Vector2 toV) {
    World b2dWorld = body.getWorld();
    hitting = false;

    RayCastCallback rayCastCallback = new RayCastCallback() {

        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            if (fixture.getBody() == body) {
                return 1;
            }

            if (fraction < 1.0f && fixture.getFilterData().categoryBits == GameManager.BOMB_BIT) {
                hitting = true;
            }
            return 0;
        }
    };

    for (int i = 0; i < 3; i++) {
        Vector2 tmpV = new Vector2(toV);
        b2dWorld.rayCast(rayCastCallback, fromV, tmpV.add(0, (1 - i) * 0.4f));
    }
    return hitting;
}
 
Example 7
Source Project: riiablo   Source File: ClientEntityFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int createPlayer(CharData charData, Vector2 position) {
  int id = super.createPlayer(charData, position);
  mCofComponentDescriptors.create(id);
  mAnimationWrapper.create(id);
  mBBoxWrapper.create(id).box = mAnimationWrapper.get(id).animation.getBox();
  mBox2DBody.create(id);
  return id;
}
 
Example 8
Source Project: gdx-ai   Source File: Scene2dFlockingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void draw () {
	if (drawDebug) {
		Steerable<Vector2> steerable = characters.get(0);
		shapeRenderer.begin(ShapeType.Line);
		shapeRenderer.setColor(0, 1, 0, 1);
		float angle = char0Proximity.getAngle() * MathUtils.radiansToDegrees;
		shapeRenderer.arc(steerable.getPosition().x, steerable.getPosition().y, char0Proximity.getRadius(),
			steerable.getOrientation() * MathUtils.radiansToDegrees - angle / 2f + 90f, angle);
		shapeRenderer.end();
	}
}
 
Example 9
Source Project: martianrun   Source File: WorldUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Body createRunner(World world) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(new Vector2(Constants.RUNNER_X, Constants.RUNNER_Y));
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(Constants.RUNNER_WIDTH / 2, Constants.RUNNER_HEIGHT / 2);
    Body body = world.createBody(bodyDef);
    body.setGravityScale(Constants.RUNNER_GRAVITY_SCALE);
    body.createFixture(shape, Constants.RUNNER_DENSITY);
    body.resetMassData();
    body.setUserData(new RunnerUserData(Constants.RUNNER_WIDTH, Constants.RUNNER_HEIGHT));
    shape.dispose();
    return body;
}
 
Example 10
Source Project: ud406   Source File: GigaGal.java    License: MIT License 5 votes vote down vote up
public GigaGal() {
    position = new Vector2(20, 20);
    lastFramePosition = new Vector2(position);
    velocity = new Vector2();
    jumpState = JumpState.FALLING;
    facing = Facing.RIGHT;
    walkState = WalkState.STANDING;
}
 
Example 11
Source Project: ud406   Source File: LevelLoader.java    License: MIT License 5 votes vote down vote up
private static Vector2 extractXY(JSONObject object) {

        Number x = (Number) object.get(Constants.LEVEL_X_KEY);
        Number y = (Number) object.get(Constants.LEVEL_Y_KEY);

        return new Vector2(
                (x == null) ? 0 : x.floatValue(),
                (y == null) ? 0 : y.floatValue()
        );
    }
 
Example 12
Source Project: gdx-ai   Source File: Box2dRaycastCollisionDetector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean findCollision (Collision<Vector2> outputCollision, Ray<Vector2> inputRay) {
	callback.collided = false;
	if (!inputRay.start.epsilonEquals(inputRay.end, MathUtils.FLOAT_ROUNDING_ERROR)) {
		callback.outputCollision = outputCollision;
		world.rayCast(callback, inputRay.start, inputRay.end);
	}
	return callback.collided;
}
 
Example 13
Source Project: bladecoder-adventure-engine   Source File: ScnWidget.java    License: Apache License 2.0 5 votes vote down vote up
public void localToWorldCoords(Vector2 coords) {
	localToStageCoordinates(coords);
	getStage().stageToScreenCoordinates(coords);

	tmpV3.set(coords.x, coords.y, 0);
	camera.unproject(tmpV3, getX(), getY(), getWidth(), getHeight());
	coords.set(tmpV3.x, tmpV3.y);
}
 
Example 14
Source Project: bladecoder-adventure-engine   Source File: GotoAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If 'player' is far from 'actor', we bring it close. If 'player' is closed
 * from 'actor' do nothing.
 * 
 * TODO: DOESN'T WORK NOW
 * 
 * @param player
 * @param actor
 */
@SuppressWarnings("unused")
private void goNear(CharacterActor player, BaseActor actor, ActionCallback cb) {
	Rectangle rdest = actor.getBBox().getBoundingRectangle();

	// Vector2 p0 = new Vector2(player.getSprite().getX(),
	// player.getSprite().getY());
	Vector2 p0 = new Vector2(player.getX(), player.getY());

	// calculamos el punto más cercano al objeto
	Vector2 p1 = new Vector2(rdest.x, rdest.y); // izquierda
	Vector2 p2 = new Vector2(rdest.x + rdest.width, rdest.y); // derecha
	Vector2 p3 = new Vector2(rdest.x + rdest.width / 2, rdest.y); // centro
	float d1 = p0.dst(p1);
	float d2 = p0.dst(p2);
	float d3 = p0.dst(p3);
	Vector2 pf;

	if (d1 < d2 && d1 < d3) {
		pf = p1;
	} else if (d2 < d1 && d2 < d3) {
		pf = p2;
	} else {
		pf = p3;
	}

	player.goTo(pf, cb, ignoreWalkZone);
}
 
Example 15
Source Project: riiablo   Source File: HoveredManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void process(int entityId) {
  BBox box = mBBoxWrapper.get(entityId).box;
  if (box == null) return;
  Vector2 position = mPosition.get(entityId).position;
  iso.toScreen(tmpVec2.set(position));
  float x = tmpVec2.x + box.xMin;
  float y = tmpVec2.y - box.yMax;
  boolean b = x <= coords.x && coords.x <= x + box.width
           && y <= coords.y && coords.y <= y + box.height;
  setHovered(entityId, b);
}
 
Example 16
Source Project: ud406   Source File: GigaGal.java    License: MIT License 5 votes vote down vote up
public GigaGal() {
    position = new Vector2(20, 20);
    velocity = new Vector2();
    jumpState = JumpState.FALLING;
    facing = Facing.RIGHT;

    // TODO: Initialize walkState

}
 
Example 17
Source Project: dice-heroes   Source File: ViewController.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Vector2 stageToWorldCoordinates(Vector2 input) {
    root.stageToLocalCoordinates(input);
    input.scl(1 / ViewController.CELL_SIZE);
    int x = MathUtils.floor(input.x);
    int y = MathUtils.floor(input.y);
    if (input.x < 0) {
        x = -Math.abs(x);
    }
    if (input.y < 0) {
        y = -Math.abs(y);
    }
    input.set(x, y);
    return input;
}
 
Example 18
Source Project: Entitas-Java   Source File: FixtureDefBuilder.java    License: MIT License 5 votes vote down vote up
public FixtureDefBuilder boxShape(float hx, float hy, Vector2 center, float angleInRadians) {
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(hx, hy, center, angleInRadians);
    fixtureDef.shape = shape;
    return this;

}
 
Example 19
Source Project: uracer-kotd   Source File: MapUtils.java    License: Apache License 2.0 5 votes vote down vote up
public Vector2 pxToTile (float x, float y) {
	retTile.set(x, y);
	retTile.scl(invTileWidth);
	retTile.y = mapHeight - retTile.y;
	VMath.truncateToInt(retTile);
	return retTile;
}
 
Example 20
Source Project: ud406   Source File: Level.java    License: MIT License 5 votes vote down vote up
private void initDebugLevel() {
    platforms.add(new Platform(15, 100, 30, 20));
    platforms.add(new Platform(75, 90, 100, 65));
    platforms.add(new Platform(35, 55, 50, 20));
    platforms.add(new Platform(10, 20, 20, 9));

    gigaGal = new GigaGal(new Vector2(15, 40));

}
 
Example 21
Source Project: jorbs-spire-mod   Source File: TargettingArrowUi.java    License: MIT License 5 votes vote down vote up
public TargettingArrowUi()
{
    this.isHidden = false;
    for (int i = 0; i < this.points.length; i++) {
        this.points[i] = new Vector2();
    }
}
 
Example 22
Source Project: GdxDemo3D   Source File: GameStage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Vector2 screenToStageCoordinates(Vector2 screenCoords) {
	tmp.set(screenCoords.x, screenCoords.y, 1);
	cameraUI.unproject(tmp, viewport.getScreenX(), viewport.getScreenY(),
			viewport.getScreenWidth(), viewport.getScreenHeight());
	screenCoords.set(tmp.x, tmp.y);
	return screenCoords;
}
 
Example 23
Source Project: bladecoder-adventure-engine   Source File: SayAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean run(VerbRunner cb) {
	float x = TextManager.POS_SUBTITLE, y = TextManager.POS_SUBTITLE;
	Color color = null;

	if (text == null)
		return false;

	InteractiveActor a = (InteractiveActor) w.getCurrentScene().getActor(actor, false);

	if (type == Text.Type.TALK && a != null) {
		Rectangle boundingRectangle = a.getBBox().getBoundingRectangle();

		x = boundingRectangle.getX() + boundingRectangle.getWidth() / 2;
		y = boundingRectangle.getY() + boundingRectangle.getHeight();

		color = ((CharacterActor) a).getTextColor();
		
		Vector2 talkingTextPos = ((CharacterActor) a).getTalkingTextPos();
		
		if(talkingTextPos != null) {
			x += talkingTextPos.x;
			y += talkingTextPos.y;
		}
	}

	w.getCurrentScene().getTextManager().addText(text, x, y, queue, type, color, style,
			a != null ? a.getId() : actor, voiceId, animation, wait?cb:null);

	return wait;

}
 
Example 24
Source Project: ud406   Source File: GigaGal.java    License: MIT License 5 votes vote down vote up
public GigaGal(Vector2 spawnLocation, Level level) {
    this.spawnLocation = spawnLocation;
    this.level = level;
    position = new Vector2();
    lastFramePosition = new Vector2();
    velocity = new Vector2();
    init();
}
 
Example 25
Source Project: ud406   Source File: GigaGal.java    License: MIT License 5 votes vote down vote up
public GigaGal(Vector2 spawnLocation, Level level) {
    this.spawnLocation = spawnLocation;
    this.level = level;
    position = new Vector2();
    lastFramePosition = new Vector2();
    velocity = new Vector2();
    init();
}
 
Example 26
Source Project: RuinsOfRevenge   Source File: TmxObjectsLoader.java    License: MIT License 5 votes vote down vote up
public static void main(String... args) throws IOException {
	GdxNativesLoader.load();
	Physics physics = new Physics(Vector2.Zero, true);
	File mapfile = new File("data/maps/newmap/map005.tmx");
	Element mapXML = new XmlReader().parse(new FileInputStream(mapfile));
	System.out.println(mapXML);

	new TmxObjectsLoader(mapXML)
		.loadToPhysics(physics, 32, 32, 50, 50);
}
 
Example 27
Source Project: riiablo   Source File: IsometricCamera.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Rounds tile coords to the closest integer tile coords from the specified float tile coords.
 */
public Vector2 toTile50(float x, float y, Vector2 dst) {
  x += tileOffset.x;
  y += tileOffset.y;
  dst.x = x < 0 ? MathUtils.round(x) : MathUtils.roundPositive(x);
  dst.y = y < 0 ? MathUtils.round(y) : MathUtils.roundPositive(y);
  return dst;
}
 
Example 28
Source Project: tilt-game-android   Source File: GameLevelController.java    License: MIT License 5 votes vote down vote up
private void checkCollisionSound(Contact contact, Body bodyA, Body bodyB) {
    WorldManifold manifold = contact.getWorldManifold();
    Vector2 contactPoint = manifold.getPoints()[0];
    Vector2 vel1 = bodyA.getLinearVelocityFromWorldPoint(contactPoint);
    Vector2 vel2 = bodyB.getLinearVelocityFromWorldPoint(contactPoint);
    Vector2 impactVelocity = vel1.sub(vel2);
    float impactLen = impactVelocity.len();
    if (impactLen > MIN_BALL_SOUND_SPEED) {
        float dot = Math.abs(impactVelocity.dot(manifold.getNormal()));
        if (dot > MIN_IMPACT_SOUND_SPEED) {
            float volume = (float) Math.min((dot - MIN_IMPACT_SOUND_SPEED) / MAX_IMPACT_SOUND_SPEED, 1.0);
            SoundManager.getInstance().play(R.raw.bounce_1, volume);
        }
    }
}
 
Example 29
Source Project: ud406   Source File: GigaGal.java    License: MIT License 5 votes vote down vote up
public GigaGal(Vector2 spawnLocation, Level level) {
    this.spawnLocation = spawnLocation;
    this.level = level;
    position = new Vector2();
    lastFramePosition = new Vector2();
    velocity = new Vector2();
    init();
}
 
Example 30
Source Project: TerraLegion   Source File: ChunkManager.java    License: MIT License 4 votes vote down vote up
/**
 * Recursive method that searches in a specified direction for a block.
 *
 * @param position The last position checked
 * @param direction The direction to search
 * @param origin The original position to check against the maxReach
 * @param maxReach The max pixels that the search can go
 * @return The tile position of a block if found; null if nothing found within reach
 */
private Vector2 findBlock(ToolItem tool, Vector2 position, Vector2 direction, Vector2 origin, float maxReach, float xCount, float yCount) {
	xCount += direction.x; //Add direction
	yCount += direction.y; //Add direction
	boolean newVal = false; //Flag to see if we switch blocks

	if (xCount >= 1 || xCount <= -1) { //If we went left or right of the last tile
		xCount = 0; //reset
		position.add((direction.x < 0 ? -1 : 1) * ChunkManager.TILE_SIZE, 0); //Go over a tile
		newVal = true; //set flag
	}

	if (yCount >= 1 || yCount <= -1) { //If we went up or down from the last tile
		yCount = 0; //reset
		position.add(0, (direction.y < 0 ? -1 : 1) * ChunkManager.TILE_SIZE); //Go vertical
		newVal = true; //set flag
	}

	if (origin.dst(position) > maxReach) { //If we're too far from the origin then return nothing
		return null;
	}

	if (!newVal) { //If we didn't change blocks we're checking, go to the next revolution
		return findBlock(tool, position, direction, origin, maxReach, xCount, yCount);
	}

	int tx = pixelToTilePosition(position.x);
	int ty = pixelToTilePosition(position.y);

	BlockType type = getBlockFromTilePos(tx, ty);
	if ((tool != null && type != BlockType.AIR)) { // we found a block
		if (tool.canDamageBlock(type)) {
			return Vector2Factory.instance.getVector2(tx, ty); //Return the tile position
		} else {
			return null;
		}
	} else if (tool == null && type != BlockType.AIR) { //Doing a search without a tool bounding the selection
		return Vector2Factory.instance.getVector2(tx, ty); //Return the tile position
	} else {
		return findBlock(tool, position, direction, origin, maxReach, xCount, yCount); //Keep searching
	}
}