UNPKG

toosoon-utils

Version:
94 lines (93 loc) 2.65 kB
import { lerp } from '../../maths'; import { Vector2 } from '../geometry'; import Curve from './Curve'; /** * Utility class for manipulating lines * * @exports * @class LineCurve * @extends Curve */ export default class LineCurve extends Curve { type = 'LineCurve'; /** * X-axis coordinate of the start point */ x1; /** * Y-axis coordinate of the start point */ y1; /** * X-axis coordinate of the end point */ x2; /** * Y-axis coordinate of the end point */ y2; /** * @param {number} x1 X-axis coordinate of the start point * @param {number} y1 Y-axis coordinate of the start point * @param {number} x2 X-axis coordinate of the end point * @param {number} y2 Y-axis coordinate of the end point */ constructor(x1, y1, x2, y2) { super(); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } /** * Interpolate a point on this curve * * @param {number} t Normalized time value to interpolate * @returns {Vector2} Interpolated coordinates on this curve */ getPoint(t) { return new Vector2(...LineCurve.interpolate(t, this.x1, this.y1, this.x2, this.y2)); } /** * Interpolate a point on this line * * @param {number} u Normalized position value to interpolate * @returns {Vector2} Interpolated coordinates on this line */ getPointAt(u) { return this.getPoint(u); } /** * Compute an unit vector tangent for a given normalized time value * * @param {number} t Normalized time value * @returns {Vector2} Tangent vector */ getTangent(t) { return new Vector2(...Vector2.sub([this.x1, this.y1], [this.x2, this.y2])).normalize(); } /** * Compute an unit vector tangent for a given normalized position value * * @param {number} u Normalized position value * @returns {Vector2} Tangent vector */ getTangentAt(u) { return this.getTangent(u); } /** * Interpolate a point on a line * * @param {number} t Normalized time value to interpolate * @param {number} x1 X-axis coordinate of the start point * @param {number} y1 Y-axis coordinate of the start point * @param {number} x2 X-axis coordinate of the end point * @param {number} y2 Y-axis coordinate of the end point * @returns {Point2} Interpolated coordinates on the line */ static interpolate(t, x1, y1, x2, y2) { const x = lerp(t, x1, x2); const y = lerp(t, y1, y2); return [x, y]; } }