Skip to content

Commit

Permalink
Update vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
igr committed Mar 23, 2024
1 parent 5903470 commit 325de4d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
8 changes: 4 additions & 4 deletions gartwork/src/main/kotlin/dev/oblac/gart/math/vector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ data class Vector(val x: Float, val y: Float) {
operator fun div(scalar: Float) = Vector(x / scalar, y / scalar)
fun dot(other: Vector) = x * other.x + y * other.y
fun cross(other: Vector) = x * other.y - y * other.x
fun length() = fastSqrt(x * x + y * y)
fun magnitude() = length()
fun normalize() = this / length()

val magnitude by lazy { fastSqrt(x * x + y * y) }
fun normalize() = this / magnitude
fun rotate(angle: Float) = Vector(
x * cos(angle) - y * sin(angle),
x * sin(angle) + y * cos(angle)
Expand All @@ -22,7 +22,7 @@ data class Vector(val x: Float, val y: Float) {
/**
* Returns the angle of the vector in radians.
*/
fun angle() = atan2(y, x)
val angle by lazy { atan2(y, x) }

companion object {
val ZERO = Vector(0f, 0f)
Expand Down
15 changes: 15 additions & 0 deletions gartwork/src/test/kotlin/dev/oblac/gart/math/VectorTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package dev.oblac.gart.math

import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

class VectorTest {

@Test
fun testAngle() {
assertEquals(0f, Vector(1f, 0f).angle, 0.0001f)
assertEquals(PIf / 2, Vector(0f, 1f).angle, 0.0001f)
assertEquals(PIf, Vector(-1f, 0f).angle, 0.0001f)
assertEquals(-PIf / 2, Vector(0f, -1f).angle, 0.0001f) // ! important
}
}

0 comments on commit 325de4d

Please sign in to comment.