Java Code Examples for com.badlogic.gdx.math.Vector2#scl()

The following examples show how to use com.badlogic.gdx.math.Vector2#scl() . 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 check out the related API usage on the sidebar.
Example 1
Source File: AnimatePositionSystem.java    From Entitas-Java with MIT License 6 votes vote down vote up
public void moveFocused(Vector2 center, Body body) {
    MoveData moveData = new MoveData();
    body.setLinearVelocity(new Vector2());
    moveData.start = body.getWorldCenter().cpy();
    moveData.direction = new Vector2(center.x - moveData.start.x, center.y - moveData.start.y);
    moveData.current = 1;
    moveData.total = 10;

    if (moveData.current == moveData.total + 1) {
        body.setLinearVelocity(new Vector2());
        return;
    }

    int t = easeInOut(moveData.current, 0, 1, moveData.total);

    Vector2 sEnd = moveData.direction.cpy();
    sEnd.scl(t);
    sEnd.add(moveData.start.cpy());

    Vector2 sStart = body.getWorldCenter();

    sEnd.sub(sStart);
    sEnd.scl(60);
    moveData.current++;
    body.setLinearVelocity(sEnd);
}
 
Example 2
Source File: CommonKeywordIconsPatches.java    From StSLib with MIT License 5 votes vote down vote up
private static void DrawOnCardAuto(SpriteBatch sb, AbstractCard card, Texture img, Vector2 offset, float width, float height, Color color, float alpha, float scaleModifier)
{
    if (card.angle != 0)
    {
        offset.rotate(card.angle);
    }

    offset.scl(Settings.scale * card.drawScale);

    DrawOnCardCentered(sb, card, new Color(color.r, color.g, color.b, alpha), img, card.current_x + offset.x, card.current_y + offset.y, width, height, scaleModifier);
}
 
Example 3
Source File: GameTrack.java    From uracer-kotd with Apache License 2.0 5 votes vote down vote up
/** Returns a value in the [-1,1] range, meaning the specified car is following the path with a confidence value as expressed by
	 * the returned value.
	 * @param car
	 * @return The confidence value with which a car is following the current waypoint path. */
	public float getTrackRouteConfidence (Car car) {
		TrackState state = car.getTrackState();

		// car is on the expected path, now check for the correct heading
		if (state.onExpectedPath) {
			TrackSector s = sectors[state.curr];
			Vector2 heading = VMath.fromRadians(car.getWorldOrientRads());
			Vector2 dir = tmp.set(s.nLeading);

			// switch coordinate space and rotate it so that both the car and the track sector converge
			// to the same value when they are ~parallel and pointing to the same direction
			dir.scl(-1, 1);

			float dot = dir.dot(heading);

			// @off
//			Gdx.app.log("GameTrack", "dir=" + NumberString.formatSmall(dir.x) + "," + NumberString.formatSmall(dir.y)
//				+ ", heading=" + NumberString.formatSmall(heading.x) + "," + NumberString.formatSmall(heading.x) + ", dot="
//				+ NumberString.formatSmall(dot));
			// @on

			return dot;
		}

		return -1;
	}
 
Example 4
Source File: Piece.java    From Klooni1010 with GNU General Public License v3.0 5 votes vote down vote up
Vector2 calculateGravityCenter() {
    int filledCount = 0;
    Vector2 result = new Vector2();
    for (int i = 0; i < cellRows; ++i) {
        for (int j = 0; j < cellCols; ++j) {
            if (shape[i][j]) {
                filledCount++;
                result.add(
                        pos.x + j * cellSize - cellSize * 0.5f,
                        pos.y + i * cellSize - cellSize * 0.5f);
            }
        }
    }
    return result.scl(1f / filledCount);
}
 
Example 5
Source File: ViewController.java    From dice-heroes with 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 6
Source File: WorldBodyUtils.java    From killingspree with MIT License 5 votes vote down vote up
public void destroyEntities(ServerBomb bomb, float radius, Vector2 position) {
    Body body = bomb.body;
    circle.set(position, radius);
    for (ServerEntity entity: worldManager.entities) {
        if (entity.body == body || entity.body.toDestroy) {
            continue;
        }
        if (Intersector.overlaps(circle, entity.body.rectangle)) {
            Vector2 step = entity.body.getPosition();
            float length = position.dst(step);
            step.sub(position);
            float max = Math.max(step.x, step.y);
            step.scl(4 / max);
            Body otherBody = Ray.findBody(world,
                    body, step, length, true);
            if (otherBody == null) {
                if (entity instanceof LivingCategory) {
                    if (((LivingCategory)entity.body.getUserData()).kill()) {
                        if (bomb.bomber != entity.body.getUserData())
                            bomb.bomber.addKill();
                        else {
                            bomb.bomber.reduceKill();
                        }
                    }
                }
            }
        }
    }
}
 
Example 7
Source File: Ray.java    From killingspree with MIT License 5 votes vote down vote up
public static Body findBody(World world, Body srcBody,
        Vector2 step, float length, boolean staticOnly) {
    Vector2 start = srcBody.getPosition();
    Body body = null;
    if (step.isZero()) {
        return null;
    }
    
    step.scl(2);
    
    float bestLength = 100000;
    length *= length;
    for (int i = 0; i < world.bodies.size(); i++) {
        if (staticOnly &&
                world.bodies.get(i).bodyType != BodyType.StaticBody) {
            continue;
        }
        if (world.bodies.get(i) == srcBody) {
            continue;
        }
        temp .set(start);
        float currentLength = temp.dst2(start);
        while (currentLength < length && currentLength < bestLength) {
            if(world.bodies.get(i).rectangle.contains((temp.x + 
                    WorldRenderer.VIEWPORT_WIDTH) % 
                    WorldRenderer.VIEWPORT_WIDTH,
                    (temp.y + WorldRenderer.VIEWPORT_HEIGHT) %
                    WorldRenderer.VIEWPORT_HEIGHT)) {
                body = world.bodies.get(i);
                bestLength = currentLength;
                continue;
            }
            temp.add(step);
            currentLength = temp.dst2(start);
        }
    }
    return body;
}
 
Example 8
Source File: ServerArrow.java    From killingspree with MIT License 5 votes vote down vote up
@Override
    public void update(float delta) {
        gravityTime -= delta;
        Vector2 velocityVector = body.getLinearVelocity();
        position.set(body.getPosition());
        Body targetBody = Ray.findBody(world.worldManager.getWorld(),
                body, tempVector.set(Math.signum(velocityVector.x), 0), 200f);
        position.set(body.getPosition());
//        Gdx.app.log(body.getPosition().toString(), target.toString());
        if (target != null) {
            Vector2 currentVelocity = body.getLinearVelocity();
            Vector2 targetVelocity = tempVector.set(target);
            targetVelocity.sub(position);
            targetVelocity.scl(1/targetVelocity.x);
            targetVelocity.scl(currentVelocity.x);
            if(Math.abs(currentVelocity.x) > 1) {
                if(Math.abs(position.x - target.x) < 200 &&
                        Math.abs(position.y - target.y) < 100) {
                    if (currentVelocity.y < targetVelocity.y) {
                        currentVelocity.y += 50f / Math.ceil(Math.abs(position.y - target.y));
                    } else {
                        currentVelocity.y -= 50f / Math.ceil(Math.abs(position.y - target.y));
                    }
                    body.setLinearVelocity(currentVelocity);
                }
            }
        }
        
        if (Utils.wrapBody(position)) {
            body.setTransform(position, 0);
        }
        
        if (gravityTime < 0) {
            body.setGravityScale(0.5f);
        }
    }
 
Example 9
Source File: BuoyancyController.java    From Codelabs with MIT License 4 votes vote down vote up
private void applyForces(Fixture fixture, Vector2[] clippedPolygon) {
	PolygonProperties polygonProperties = PolygonIntersector
			.computePolygonProperties(clippedPolygon);

	/* Get fixtures bodies */
	Body fixtureBody = fixture.getBody();
	Body fluidBody = fluidSensor.getBody();

	/* Get fluid density */
	float density = fluidSensor.getDensity();

	/* Apply buoyancy force */
	float displacedMass = fluidSensor.getDensity()
			* polygonProperties.getArea();
	Vector2 gravity = world.getGravity();
	Vector2 buoyancyForce = new Vector2(-gravity.x * displacedMass,
			-gravity.y * displacedMass);
	fixtureBody.applyForce(buoyancyForce, polygonProperties.getCentroid(),
			true);

	/* Linear drag force */
	if (linearDrag != 0) {
		fixtureBody.applyForce(gravity.rotate90(1).nor().scl(linearDrag),
				polygonProperties.getCentroid(), true);
	}

	/* Apply drag and lift forces */
	int polygonVertices = clippedPolygon.length;
	for (int i = 0; i < polygonVertices; i++) {

		/* Apply drag force */

		/* End points and mid point of the edge */
		Vector2 firstPoint = clippedPolygon[i];
		Vector2 secondPoint = clippedPolygon[(i + 1) % polygonVertices];
		Vector2 midPoint = firstPoint.cpy().add(secondPoint).scl(0.5f);

		/*
		 * Find relative velocity between the object and the fluid at edge
		 * mid point.
		 */
		Vector2 velocityDirection = new Vector2(fixtureBody
				.getLinearVelocityFromWorldPoint(midPoint)
				.sub(fluidBody.getLinearVelocityFromWorldPoint(midPoint)));
		float velocity = velocityDirection.len();
		velocityDirection.nor();

		Vector2 edge = secondPoint.cpy().sub(firstPoint);
		float edgeLength = edge.len();
		edge.nor();

		Vector2 normal = new Vector2(edge.y, -edge.x);
		float dragDot = normal.dot(velocityDirection);

		if (dragDot >= 0) {

			/*
			 * Normal don't point backwards. This is a leading edge. Store
			 * the result of multiply edgeLength, density and velocity
			 * squared
			 */
			float tempProduct = edgeLength * density * velocity * velocity;

			float drag = dragDot * fluidDrag * tempProduct;
			drag = Math.min(drag, maxFluidDrag);
			Vector2 dragForce = velocityDirection.cpy().scl(-drag);
			fixtureBody.applyForce(dragForce, midPoint, true);

			/* Apply lift force */
			float liftDot = edge.dot(velocityDirection);
			float lift = dragDot * liftDot * fluidLift * tempProduct;
			lift = Math.min(lift, maxFluidLift);
			Vector2 liftDirection = new Vector2(-velocityDirection.y,
					velocityDirection.x);
			Vector2 liftForce = liftDirection.scl(lift);
			fixtureBody.applyForce(liftForce, midPoint, true);
		}
	}
}
 
Example 10
Source File: PolygonIntersector.java    From Codelabs with MIT License 4 votes vote down vote up
public static PolygonProperties computePolygonProperties(Vector2[] polygon) {
	PolygonProperties polygonProperties = null;

	int count = polygon.length;

	if (count >= 3) {
		Vector2 centroid = new Vector2(0, 0);
		float area = 0;

		Vector2 refPoint = new Vector2(0, 0);
		float threeInverse = 1 / 3f;

		for (int i = 0; i < count; i++) {
			/*
			 * Create a new vector to represent the reference point for
			 * forming triangles. Then use refPoint, polygonVertex and
			 * thirdTriangleVertex as vertices of a triangle.
			 */
			refPoint.set(0, 0);
			Vector2 polygonVertex = polygon[i];
			Vector2 thirdTriangleVertex = i + 1 < count ? polygon[i + 1]
					: polygon[0];

			Vector2 firstDirectionVector = polygonVertex.sub(refPoint);
			Vector2 secondDirectionVector = thirdTriangleVertex
					.sub(refPoint);

			float triangleArea = firstDirectionVector
					.crs(secondDirectionVector) / 2;
			area += triangleArea;

			/* Area weighted centroid */
			centroid.add(refPoint.add(polygonVertex)
					.add(thirdTriangleVertex)
					.scl(triangleArea * threeInverse));
		}

		if (area > EPSILON) {
			centroid.scl(1 / area);
		} else {
			area = 0;
		}

		polygonProperties = new PolygonProperties(centroid, area);
	}

	return polygonProperties;
}