UNPKG

@tsparticles/path-polygon

Version:
59 lines (58 loc) 2.06 kB
import { Vector, deepExtend, getRandom } from "@tsparticles/engine"; const defaultOptions = { sides: 6, turnSteps: 20, angle: 30, }; export class PolygonPathGenerator { dirsList; options; #container; #res; constructor(container) { this.#container = container; this.#res = Vector.origin; this.dirsList = []; this.options = deepExtend({}, defaultOptions); } generate(p) { const { sides, turnSteps } = this.options; p.hexStep ??= 0; p.hexDirection ??= sides === 6 ? ((getRandom() * 3) | 0) * 2 : (getRandom() * sides) | 0; p.hexSpeed ??= p.velocity.length; if (p.hexStep % turnSteps === 0) { p.hexDirection = getRandom() > 0.5 ? (p.hexDirection + 1) % sides : (p.hexDirection + sides - 1) % sides; } p.velocity.x = 0; p.velocity.y = 0; p.hexStep++; const direction = this.dirsList[p.hexDirection]; this.#res.x = direction.x * p.hexSpeed; this.#res.y = direction.y * p.hexSpeed; return this.#res; } init() { const container = this.#container, sourceOptions = container.actualOptions.particles.move.path.options; this.options.sides = sourceOptions["sides"] > 0 ? sourceOptions["sides"] : this.options.sides; this.options.angle = sourceOptions["angle"] ?? this.options.angle; this.options.turnSteps = sourceOptions["turnSteps"] >= 0 ? sourceOptions["turnSteps"] : this.options.turnSteps; this.#createDirs(); } reset(particle) { delete particle.hexStep; delete particle.hexDirection; delete particle.hexSpeed; } update() { } #createDirs = () => { const options = this.options; this.dirsList = []; for (let i = 0; i < 360; i += 360 / options.sides) { const angle = options.angle + i; this.dirsList.push(Vector.create(Math.cos((angle * Math.PI) / 180), Math.sin((angle * Math.PI) / 180))); } }; }