Skip to content

Instantly share code, notes, and snippets.

@RazorNd
Created November 18, 2022 11:29
Show Gist options
  • Save RazorNd/3b8d3b906514bcd60055020efb8e8eb2 to your computer and use it in GitHub Desktop.
Save RazorNd/3b8d3b906514bcd60055020efb8e8eb2 to your computer and use it in GitHub Desktop.
spoiler
import kotlin.jvm.JvmStatic
import kotlin.math.sqrt
data class Vector2D(val x: Double, val y: Double) {
val length: Double
get() = sqrt(x * x + y * y)
val normalized: Vector2D
get() = check(this != ZERO) { "Zero length vector can't be normalized" }.let { this / length }
operator fun plus(other: Vector2D): Vector2D = Vector2D(x + other.x, y + other.y)
operator fun minus(other: Vector2D): Vector2D = Vector2D(x - other.x, y - other.y)
operator fun unaryMinus(): Vector2D = Vector2D(-x, -y)
operator fun times(a: Double): Vector2D = Vector2D(x * a, y * a)
private operator fun div(a: Double): Vector2D = Vector2D(x / a, y / a)
operator fun Double.times(vector: Vector2D) = vector * this
companion object {
@JvmStatic
val ZERO = Vector2D(0.0, 0.0)
}
}
fun Vector2D.changeSpeed(value: Double): Vector2D = normalized * (length + value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment