1 package com.jed.util;
2
3 import javax.annotation.Nonnull;
4
5
6
7
8
9
10
11 public final class Vector2f {
12
13
14
15
16 public float x;
17
18
19
20
21 public float y;
22
23
24
25
26 private Vector2f() {
27 super();
28 }
29
30
31
32
33
34
35 public Vector2f(float x, float y) {
36 this();
37 this.x = x;
38 this.y = y;
39 }
40
41
42
43
44
45
46 public double distance(@Nonnull final Vector2f o) {
47 double axBx = x - o.x;
48 axBx = Math.pow(axBx, 2.0d);
49 double ayBy = (y - o.y);
50 ayBy = Math.pow(ayBy, 2.0d);
51 return Math.sqrt(axBx + ayBy);
52 }
53
54
55
56
57
58
59 @Nonnull
60 public Vector2f add(@Nonnull Vector2f o) {
61 return new Vector2f(this.x + o.x, this.y + o.y);
62 }
63
64
65
66
67
68
69 @Nonnull
70 public Vector2f subtract(@Nonnull Vector2f o) {
71 return new Vector2f(o.x - this.x, o.y - this.y);
72 }
73
74
75
76
77
78 public double magnitude() {
79 return Math.sqrt((this.x * this.x) + (this.y * this.y));
80 }
81
82
83
84
85
86
87 public double angle() {
88 return Math.atan2(this.y, this.x);
89 }
90
91
92
93
94
95
96
97
98
99
100 public double dotProduct(@Nonnull Vector2f v1) {
101 return x * v1.x + y * v1.y;
102 }
103
104
105
106
107
108 @Nonnull
109 public Vector2f normalize() {
110 Vector2f v2 = new Vector2f();
111
112 double length = magnitude();
113 if (length != 0) {
114 v2.x = x / (float) length;
115 v2.y = y / (float) length;
116 }
117
118 return v2;
119 }
120
121
122
123
124
125
126 @Nonnull
127 public Vector2f scale(float scaleFactor) {
128 return new Vector2f(x * scaleFactor, y * scaleFactor);
129 }
130
131
132
133
134
135 @Nonnull
136 public Vector2f copy() {
137 return new Vector2f(x, y);
138 }
139
140 }