export default class Vector2D {

    x : number;
    y : number;

    constructor(x : number, y : number) {
        this.x = x;
        this.y = y;
    }

    cpy() {
        return new Vector2D(this.x,this.y);
    }

    len() {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    }

    len2() {
        return (this.x * this.x + this.y * this.y);
    }

    set(x : number, y : number) {
        this.x = x;
        this.y = y;
        return this;
    }

    sub(x : number, y : number) {
        this.x = this.x - x;
        this.y = this.y - y;
        return this;
    }

    nor() {
        const len = this.len();
        if(len != 0) {
            this.x /= len;
            this.y /= len;
        }
        return this;
    }

    add(x : number, y : number) {
        this.x = this.x + x;
        this.y = this.y + y;
        return this;
    }

    dot(v : Vector2D) {
        return this.x * v.x + this.y * v.y;
    }

    scl(scalar : number) {
        this.x *= scalar;
        this.y *= scalar;
        return this;
    }

    dst(v : Vector2D) {
        const x_distance = v.x - this.x;
        const y_distance = v.y - this.y;
        return Math.sqrt(x_distance * x_distance + y_distance * y_distance);
    }

    dstToCoordinates(x : number, y : number) {
        const x_distance = x - this.x;
        const y_distance = y - this.y;
        return Math.sqrt(x_distance * x_distance + y_distance * y_distance);
    }

    dst2(v : Vector2D) {
        const x_distance = v.x - this.x;
        const y_distance = v.y - this.y;
        return x_distance * x_distance + y_distance * y_distance;
    }

    limit2(limit2 : number) {
        const len2 = this.len2();
        if(len2 > limit2) {
            return this.scl(Math.sqrt(limit2 / len2));
        }
    }

    isZero() {
        return this.x == 0 && this.y == 0;
    }

}