Java examples for java.lang:Math Vector
Compute the angle between the vector (1,0) and the given vector.
/* /*w w w .j av a 2 s . c om*/ * $Id$ * * Copyright (c) 2007-13 Stephane GALLAND. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * This program is free software; you can redistribute it and/or modify */ import javax.vecmath.Vector2d; public class Main{ /** Compute the angle between the vector (1,0) and the given vector. * * @param orientation * @return the angle */ public static double toOrientationAngle(Vector2d orientation) { return signedAngle(new Vector2d(1, 0), orientation); } /** Replies the angle between the vector v1 and v2. * <p> * The replied angle is the smallest rotation angle to turn v1 to be equals to * v2. * <p> * Assumed that: <ul> * <li>signedAngle(v1,v2) == -signedAngle(v2,v2)</li> * <li>v2.equals( turnVector( v1, signedAngle(v1,v2) ) )</li> * </ul> * * @param v1 * @param v2 * @return the signed angle between v1 and v2 */ public static double signedAngle(Vector2d v1, Vector2d v2) { Vector2d a = new Vector2d(v1); if (a.length() == 0) return Double.NaN; Vector2d b = new Vector2d(v2); if (b.length() == 0) return Double.NaN; a.normalize(); b.normalize(); double cos = a.x * b.x + a.y * b.y; // A x B = |A|.|B|.sin(theta).N = sin(theta) (where N is the unit vector perpendicular to plane AB) double sin = a.x * b.y - a.y * b.x; double angle = Math.atan2(sin, cos); return angle; } }