Capsule.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. ( function () {
  2. const _v1 = new THREE.Vector3();
  3. const _v2 = new THREE.Vector3();
  4. const _v3 = new THREE.Vector3();
  5. const EPS = 1e-10;
  6. class Capsule {
  7. constructor( start = new THREE.Vector3( 0, 0, 0 ), end = new THREE.Vector3( 0, 1, 0 ), radius = 1 ) {
  8. this.start = start;
  9. this.end = end;
  10. this.radius = radius;
  11. }
  12. clone() {
  13. return new Capsule( this.start.clone(), this.end.clone(), this.radius );
  14. }
  15. set( start, end, radius ) {
  16. this.start.copy( start );
  17. this.end.copy( end );
  18. this.radius = radius;
  19. }
  20. copy( capsule ) {
  21. this.start.copy( capsule.start );
  22. this.end.copy( capsule.end );
  23. this.radius = capsule.radius;
  24. }
  25. getCenter( target ) {
  26. return target.copy( this.end ).add( this.start ).multiplyScalar( 0.5 );
  27. }
  28. translate( v ) {
  29. this.start.add( v );
  30. this.end.add( v );
  31. }
  32. checkAABBAxis( p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius ) {
  33. return ( minx - p1x < radius || minx - p2x < radius ) && ( p1x - maxx < radius || p2x - maxx < radius ) && ( miny - p1y < radius || miny - p2y < radius ) && ( p1y - maxy < radius || p2y - maxy < radius );
  34. }
  35. intersectsBox( box ) {
  36. return this.checkAABBAxis( this.start.x, this.start.y, this.end.x, this.end.y, box.min.x, box.max.x, box.min.y, box.max.y, this.radius ) && this.checkAABBAxis( this.start.x, this.start.z, this.end.x, this.end.z, box.min.x, box.max.x, box.min.z, box.max.z, this.radius ) && this.checkAABBAxis( this.start.y, this.start.z, this.end.y, this.end.z, box.min.y, box.max.y, box.min.z, box.max.z, this.radius );
  37. }
  38. lineLineMinimumPoints( line1, line2 ) {
  39. const r = _v1.copy( line1.end ).sub( line1.start );
  40. const s = _v2.copy( line2.end ).sub( line2.start );
  41. const w = _v3.copy( line2.start ).sub( line1.start );
  42. const a = r.dot( s ),
  43. b = r.dot( r ),
  44. c = s.dot( s ),
  45. d = s.dot( w ),
  46. e = r.dot( w );
  47. let t1, t2;
  48. const divisor = b * c - a * a;
  49. if ( Math.abs( divisor ) < EPS ) {
  50. const d1 = - d / c;
  51. const d2 = ( a - d ) / c;
  52. if ( Math.abs( d1 - 0.5 ) < Math.abs( d2 - 0.5 ) ) {
  53. t1 = 0;
  54. t2 = d1;
  55. } else {
  56. t1 = 1;
  57. t2 = d2;
  58. }
  59. } else {
  60. t1 = ( d * a + e * c ) / divisor;
  61. t2 = ( t1 * a - d ) / c;
  62. }
  63. t2 = Math.max( 0, Math.min( 1, t2 ) );
  64. t1 = Math.max( 0, Math.min( 1, t1 ) );
  65. const point1 = r.multiplyScalar( t1 ).add( line1.start );
  66. const point2 = s.multiplyScalar( t2 ).add( line2.start );
  67. return [ point1, point2 ];
  68. }
  69. }
  70. THREE.Capsule = Capsule;
  71. } )();