1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
12 // A small class that encapsulates a 2D vector. Provides a few simple
17 Vector2() : x_(0.0), y_(0.0) {}
18 Vector2(double x
, double y
) : x_(x
), y_(y
) {}
21 // Create a new vector that represents a - b.
22 static Vector2
Difference(const Vector2
& a
, const Vector2
& b
) {
23 Vector2
diff(a
.x() - b
.x(), a
.y() - b
.y());
27 // The magnitude of this vector.
28 double Magnitude() const {
29 return sqrt(x_
* x_
+ y_
* y_
);
32 // Add |vec| to this vector. Works in-place.
33 void Add(const Vector2
& vec
) {
38 // Normalize this vector in-place. If the vector is degenerate (size 0)
41 double mag
= Magnitude();
42 if (fabs(mag
) < std::numeric_limits
<double>::epsilon())
47 // Scale the vector in-place by |scale|.
48 void Scale(double scale
) {
53 // Clamp a vector to a maximum magnitude. Works on the vector in-place.
54 // @param max_mag The maximum magnitude of the vector.
55 void Clamp(double max_mag
) {
56 double mag
= Magnitude();
58 Scale(max_mag
/ mag
); // Does Normalize() followed by Scale(max_mag).
62 // Compute the "heading" of a vector - this is the angle in radians between
63 // the vector and the x-axis.
64 // @return {!number} The "heading" angle in radians.
65 double Heading() const {
66 double angle
= atan2(y_
, x_
);
70 // Accessors and mutators for the coordinate values.
71 double x() const { return x_
; }
72 void set_x(double x
) { x_
= x
; }
74 double y() const { return y_
; }
75 void set_y(double y
) { y_
= y
; }