drawGrid method

dynamic drawGrid()
  • Draw a grid and add it to the scene

Implementation

drawGrid() {
  if (this.scene != null) {
    var color = 0x888888;
    var multiplier = 3;
    var size, divisions, maxLength, tick;

    if (this.camera is OrthographicCamera) {
      var width = this.camera.right - this.camera.left;
      var height = this.camera.bottom - this.camera.top;

      maxLength = Math.max(width, height);
      tick = maxLength / 20;

      size = maxLength / this.camera.zoom * multiplier;
      divisions = size / tick * this.camera.zoom;
    } else if (this.camera is PerspectiveCamera) {
      var distance = this.camera.position.distanceTo(this._gizmos.position);
      var halfFovV = MathUtils.DEG2RAD * this.camera.fov * 0.5;
      var halfFovH = Math.atan((this.camera.aspect) * Math.tan(halfFovV));

      maxLength = Math.tan(Math.max(halfFovV, halfFovH)) * distance * 2;
      tick = maxLength / 20;

      size = maxLength * multiplier;
      divisions = size / tick;
    }

    if (this._grid == null) {
      this._grid = new GridHelper(size, divisions, color, color);
      this._grid.position.copy(this._gizmos.position);
      this._gridPosition.copy(this._grid.position);
      this._grid.quaternion.copy(this.camera.quaternion);
      this._grid.rotateX(Math.PI * 0.5);

      this.scene!.add(this._grid);
    }
  }
}