Skip to content

Commit

Permalink
math.vec: cleanup angle_between implementation, add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
spytheman committed Dec 13, 2024
1 parent f581bb7 commit 25905df
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
8 changes: 2 additions & 6 deletions vlib/math/vec/vec2.v
Original file line number Diff line number Diff line change
Expand Up @@ -316,13 +316,9 @@ pub fn (v Vec2[T]) manhattan_distance(u Vec2[T]) T {
// angle_between returns the angle in radians to the vector `u`.
pub fn (v Vec2[T]) angle_between(u Vec2[T]) T {
$if T is f64 {
return math.atan2(u.y * v.x - u.x * v.y, u.x * v.x - u.y * v.y)
return math.atan2(v.cross(u), v.dot(u))
} $else {
vx := f64(v.x)
vy := f64(v.y)
ux := f64(u.x)
uy := f64(u.y)
return T(math.atan2(uy * vx - ux * vy, ux * vx - uy * vy))
return T(math.atan2(f64(v.cross(u)), f64(v.dot(u))))
}
}

Expand Down
9 changes: 9 additions & 0 deletions vlib/math/vec/vec2_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,13 @@ fn test_vec2_angle_between() {
assert vec.vec2(1.0, 0.0).angle_between(vec.vec2(-1.0, -1.0)) == math.pi * 5.0 / 4.0 - 2 * math.pi
assert vec.vec2(1.0, 0.0).angle_between(vec.vec2(0.0, -1.0)) == math.pi * 6.0 / 4.0 - 2 * math.pi
assert vec.vec2(1.0, 0.0).angle_between(vec.vec2(1.0, -1.0)) == math.pi * 7.0 / 4.0 - 2 * math.pi

// check the angle between non-normalised vectors too:
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(2.0, 2.0)) == math.pi * 1.0 / 4.0
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(0.0, 2.0)) == math.pi * 2.0 / 4.0
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(-2.0, 2.0)) == math.pi * 3.0 / 4.0
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(-2.0, 0.0)) == math.pi
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(-2.0, -2.0)) == math.pi * 5.0 / 4.0 - 2 * math.pi
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(0.0, -2.0)) == math.pi * 6.0 / 4.0 - 2 * math.pi
assert vec.vec2(5.0, 0.0).angle_between(vec.vec2(2.0, -2.0)) == math.pi * 7.0 / 4.0 - 2 * math.pi
}

0 comments on commit 25905df

Please sign in to comment.