-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec2.h
66 lines (49 loc) · 1.1 KB
/
vec2.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma once
#include <cmath>
struct vec2
{
vec2(float x = 0, float y = 0)
: x(x), y(y)
{ }
vec2 operator*(float s) const
{ return vec2(x*s, y*s); }
vec2& operator*=(float s)
{ x *= s; y *= s; return *this; }
vec2 operator+(const vec2& v) const
{ return vec2(x + v.x, y + v.y); }
vec2& operator+=(const vec2& v)
{ x += v.x; y += v.y; return *this; }
vec2 operator-(const vec2& v) const
{ return vec2(x - v.x, y - v.y); }
vec2 operator-() const
{ return vec2(-x, -y); }
vec2& operator-=(const vec2& v)
{ x -= v.x; y -= v.y; return *this; }
float dot(const vec2& v) const
{ return x*v.x + y*v.y; }
float length_squared() const
{ return x*x + y*y; }
float length() const
{ return sqrtf(length_squared()); }
vec2& normalize()
{
const float EPSILON = 1e-5;
float l = length();
if (fabs(l) > EPSILON)
*this *= 1./l;
return *this;
}
vec2& set_length(float l)
{ *this *= l/length(); return *this; }
float distance(const vec2& v) const
{
vec2 d = v - *this;
return d.length();
}
float x, y;
};
inline vec2
operator*(float s, const vec2& v)
{
return vec2(s*v.x, s*v.y);
}