toosoon-utils
Version:
Utility functions & classes
94 lines (93 loc) • 2.98 kB
JavaScript
import { catmullRom } from '../../maths';
import { Vector2 } from '../geometry';
import Curve from './Curve';
/**
* Utility class for manipulating Catmull-Rom curves
*
* @exports
* @class CatmullRomCurve
* @extends Curve
*/
export default class CatmullRomCurve extends Curve {
type = 'CatmullRomCurve';
/**
* X-axis coordinate of the start point
*/
x1;
/**
* Y-axis coordinate of the start point
*/
y1;
/**
* X-axis coordinate of the first control point
*/
cp1x;
/**
* Y-axis coordinate of the first control point
*/
cp1y;
/**
* X-axis coordinate of the second control point
*/
cp2x;
/**
* Y-axis coordinate of the second control point
*/
cp2y;
/**
* 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} cp1x X-axis coordinate of the first control point
* @param {number} cp1y Y-axis coordinate of the first control point
* @param {number} cp2x X-axis coordinate of the second control point
* @param {number} cp2y Y-axis coordinate of the second control point
* @param {number} x2 X-axis coordinate of the end point
* @param {number} y2 Y-axis coordinate of the end point
*/
constructor(x1, y1, cp1x, cp1y, cp2x, cp2y, x2, y2) {
super();
this.x1 = x1;
this.y1 = y1;
this.cp1x = cp1x;
this.cp1y = cp1y;
this.cp2x = cp2x;
this.cp2y = cp2y;
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(...CatmullRomCurve.interpolate(t, this.x1, this.y1, this.cp1x, this.cp1y, this.cp2x, this.cp2y, this.x2, this.y2));
}
/**
* Interpolate a point on a Catmull-Rom curve
*
* @param {number} x1 X-axis coordinate of the start point
* @param {number} y1 Y-axis coordinate of the start point
* @param {number} cp1x X-axis coordinate of the first control point
* @param {number} cp1y Y-axis coordinate of the first control point
* @param {number} cp2x X-axis coordinate of the second control point
* @param {number} cp2y Y-axis coordinate of the second control 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 curve
*/
static interpolate(t, x1, y1, cp1x, cp1y, cp2x, cp2y, x2, y2) {
const x = catmullRom(t, x1, cp1x, cp2x, x2);
const y = catmullRom(t, y1, cp1y, cp2y, y2);
return [x, y];
}
}