Advertisement
Mangus875

JavaScript Bezier Function

Dec 5th, 2023
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // typeof but better
  2. function getType(obj) {
  3.     if (obj === null) return 'null';
  4.     if (obj === undefined) return 'undefined';
  5.     return obj.__proto__.constructor.name;
  6. }
  7.  
  8. class Vector2 {
  9.     constructor(x=0, y=0) {
  10.         this.x = x;
  11.         this.y = y;
  12.     }
  13.    
  14.     lerp(t, v1, v2) {
  15.         return new Vector2(lerp(t, a.x, b.x), lerp(t, a.y, b.y));
  16.     }
  17. }
  18.  
  19. // lerp functions
  20. const lerp = (t, a, b) => t*(b-a)+a;
  21. const slurp = (t, a, b) => new Vector2(lerp(t, a.x, b.x), lerp(t, a.y, b.y));
  22.  
  23. function bezier(t, ...pts) {
  24.     let lerpFunc = lerp;
  25.     if (getType(pts[0]) == 'Vector2') {
  26.         lerpFunc = slurp;
  27.     }
  28.    
  29.     if (pts.length == 2) {
  30.         return lerpFunc(t, pts[0], pts[1]);
  31.     }
  32.    
  33.     let bez1 = [...pts];
  34.     let bez2 = [...pts];
  35.     bez1.pop();
  36.     bez2.shift();
  37.    
  38.     return lerpFunc(t, bezier(t, ...bez1), bezier(t, ...bez2));
  39. }
  40.  
  41. console.log(bezier(0.5, 1, 0, 1, 0));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement