Created
November 18, 2022 11:29
-
-
Save RazorNd/3b8d3b906514bcd60055020efb8e8eb2 to your computer and use it in GitHub Desktop.
spoiler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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