Stuart Scott | c67f78d | 2013-04-08 13:11:04 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2013 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | * in compliance with the License. You may obtain a copy of the License at |
| 6 | * |
| 7 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | * |
| 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | * or implied. See the License for the specific language governing permissions and limitations under |
| 12 | * the License. |
| 13 | */ |
| 14 | #include "Vector2D.h" |
| 15 | |
| 16 | #include <math.h> |
| 17 | |
| 18 | Vector2D::Vector2D() : |
| 19 | mX(0), mY(0) { |
| 20 | } |
| 21 | |
| 22 | Vector2D::Vector2D(float x, float y) : |
| 23 | mX(x), mY(y) { |
| 24 | } |
| 25 | |
| 26 | Vector2D Vector2D::copy() { |
| 27 | Vector2D v(mX, mY); |
| 28 | return v; |
| 29 | } |
| 30 | |
| 31 | void Vector2D::add(const Vector2D& v) { |
| 32 | mX += v.mX; |
| 33 | mY += v.mY; |
| 34 | } |
| 35 | |
| 36 | void Vector2D::sub(const Vector2D& v) { |
| 37 | mX -= v.mX; |
| 38 | mY -= v.mY; |
| 39 | } |
| 40 | |
| 41 | void Vector2D::scale(float s) { |
| 42 | mX *= s; |
| 43 | mY *= s; |
| 44 | } |
| 45 | |
| 46 | float Vector2D::distance(const Vector2D& v) { |
| 47 | float dx = mX - v.mX; |
| 48 | float dy = mY - v.mY; |
| 49 | return (float) sqrt(dx * dx + dy * dy); |
| 50 | } |
| 51 | |
| 52 | void Vector2D::normalize() { |
| 53 | float m = magnitude(); |
| 54 | if (m > 0) { |
| 55 | scale(1 / m); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | void Vector2D::limit(float max) { |
| 60 | if (magnitude() > max) { |
| 61 | normalize(); |
| 62 | scale(max); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | float Vector2D::magnitude() { |
| 67 | return (float) sqrt(mX * mX + mY * mY); |
| 68 | } |