HTML5 Game - Canvas Animation Vector2D class

Description

Vector2D class

Demo

ResultView the demo in separate window

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Vector examples</title>
<link rel="stylesheet" href="style.css">
</head>// w ww .ja  v  a2 s  . com
<body>
<p>Check console for the result.</p>
<script>
class Vector2D {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    lengthSquared() {
        return this.x * this.x + this.y * this.y;
    }

    length() {
        return Math.sqrt(this.lengthSquared());
    }

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

    negate() {
        this.x = -this.x;
        this.y = -this.y;
    }

    normalize() {
        const length = this.length();
        if (length > 0) {
            this.x /= length;
            this.y /= length;
        }
        return this.length();
    }

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

    incrementBy({
        x,
        y
    }) {
        this.x += x;
        this.y += y;
    }

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

    decrementBy({
        x,
        y
    }) {
        this.x -= x;
        this.y -= y;
    }

    scaleBy(k) {
        this.x *= k;
        this.y *= k;
    }

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

// STATIC METHODS
Vector2D.distance = (vec1, vec2) => (vec1.subtract(vec2)).length()
Vector2D.angleBetween = (vec1, vec2) => Math.acos(vec1.dotProduct(vec2) / (vec1.length() * vec2.length()))
let vec1 = new Vector2D(1, 1);
let vec2 = new Vector2D(1, 0);
console.log(vec1.length()); // magnitude of vec1 
console.log(vec1.lengthSquared()); // magnitude squared of vec1      
console.log(Vector2D.angleBetween(vec1, vec2) * 180 / Math.PI); // static method that returns the angle between two vectors
console.log(vec1.dotProduct(vec2)); // returns dot product of vec1 with vec2  
  
  </script>
</body>
</html>

Related Topics