Sets the length of a vector. - Java java.lang

Java examples for java.lang:Math Vector

Description

Sets the length of a vector.

Demo Code


//package com.java2s;

import java.awt.geom.Point2D;

public class Main {
    /**//from w w  w.j av  a2s  .  c o m
     * Sets the length of a vector.
     * 
     * @param v The vector.
     * @param l The new length.
     * @return The vector with the given length.
     */
    public static Point2D setLength(final Point2D v, final double l) {
        return mulVec(v, l / getLength(v));
    }

    /**
     * Multiplies a point with a scalar.
     * 
     * @param v Point.
     * @param s Scalar.
     * @return The scaled vector.
     */
    public static Point2D mulVec(final Point2D v, final double s) {
        return new Point2D.Double(v.getX() * s, v.getY() * s);
    }

    /**
     * Calculates the length of a vector.
     * 
     * @param v The vector.
     * @return The length.
     */
    public static double getLength(final Point2D v) {
        return Math.sqrt(getLengthSq(v));
    }

    /**
     * Calculates the squared length of a vector.
     * 
     * @param v The vector.
     * @return The squared length.
     */
    public static double getLengthSq(final Point2D v) {
        return v.getX() * v.getX() + v.getY() * v.getY();
    }
}

Related Tutorials