Previous 10 Next

Building blocks

We create some abstractions that we use throughout the book.

Vectors

Vectors are convenient for representing both positions and directions.

src/Vector2.ts
import { tVector2 } from "./temporaryObjects";

export class Vector2 {
  constructor(
    public x: number = 0,
    public y: number = 0
  ) { }

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

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

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

export function dot(a: Vector2, b: Vector2) {
  return a.x*b.x+a.y*b.y
}

export function subtract(a: Vector2, b: Vector2) {
  return tVector2.get(a.x-b.x, a.y-b.y)
}

Rectangles

The game is mostly built up by rectangles.

src/Rectangle.ts
export class Rectangle {
  constructor(
    public x: number,
    public y: number,
    public width: number,
    public height: number
  ) { }

  set(x: number, y: number, width: number, height: number) {
    this.x = x
    this.y = y
    this.width = width
    this.height = height
  }
}

Lines

A line segment between two points.

src/Line.ts
import { Vector2 } from "./Vector2";

export class Line {
  constructor(
    public p0: Vector2,
    public p1: Vector2
  ) { }
}
Previous 10 Next