Rotates a point around the center such that the result has the given distance to the original point. - Java java.lang

Java examples for java.lang:Math Geometry Distance

Description

Rotates a point around the center such that the result has the given distance to the original point.

Demo Code


//package com.java2s;
import java.awt.geom.AffineTransform;

import java.awt.geom.Point2D;

public class Main {
    /**/*from   w  ww  . j  av a  2  s.  c om*/
     * Rotates a point around the center such that the result has the given
     * distance to the original point.
     * 
     * @param pos The point to rotate.
     * @param center The center.
     * @param dist The distance. Positive values rotate in clockwise direction.
     * @return The point that has the given distance to the original point.
     * @throws IllegalArgumentException When the distance is longer than the
     *           diameter.
     */
    public static Point2D rotate(final Point2D pos, final Point2D center,
            final double dist) {
        final double f = dist > 0 ? 1 : -1;
        final double dSq = dist * dist;
        final Point2D rad = subVec(pos, center);
        final double radSq = getLengthSq(rad);
        if (dSq > 4 * radSq)
            return subVec(center, rad);
        return rotateByAngle(pos, center,
                f * Math.acos(1 - dSq * 0.5 / radSq));
    }

    /**
     * Subtracts two points.
     * 
     * @param a Point.
     * @param b Point.
     * @return The difference vector.
     */
    public static Point2D subVec(final Point2D a, final Point2D b) {
        return new Point2D.Double(a.getX() - b.getX(), a.getY() - b.getY());
    }

    /**
     * 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();
    }

    /**
     * Rotates a point a given angle around the center.
     * 
     * @param pos The point to rotate.
     * @param center The center.
     * @param angle The angle.
     * @return The rotated point.
     */
    public static Point2D rotateByAngle(final Point2D pos,
            final Point2D center, final double angle) {
        final AffineTransform at = AffineTransform.getRotateInstance(angle,
                center.getX(), center.getY());
        return at.transform(pos, null);
    }
}

Related Tutorials