Raycaster.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { Ray } from '../math/Ray.js';
  2. import { Layers } from './Layers.js';
  3. class Raycaster {
  4. constructor( origin, direction, near = 0, far = Infinity ) {
  5. this.ray = new Ray( origin, direction );
  6. // direction is assumed to be normalized (for accurate distance calculations)
  7. this.near = near;
  8. this.far = far;
  9. this.camera = null;
  10. this.layers = new Layers();
  11. this.params = {
  12. Mesh: {},
  13. Line: { threshold: 1 },
  14. LOD: {},
  15. Points: { threshold: 1 },
  16. Sprite: {}
  17. };
  18. }
  19. set( origin, direction ) {
  20. // direction is assumed to be normalized (for accurate distance calculations)
  21. this.ray.set( origin, direction );
  22. }
  23. setFromCamera( coords, camera ) {
  24. if ( camera && camera.isPerspectiveCamera ) {
  25. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  26. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27. this.camera = camera;
  28. } else if ( camera && camera.isOrthographicCamera ) {
  29. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  31. this.camera = camera;
  32. } else {
  33. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  34. }
  35. }
  36. intersectObject( object, recursive = true, intersects = [] ) {
  37. intersectObject( object, this, intersects, recursive );
  38. intersects.sort( ascSort );
  39. return intersects;
  40. }
  41. intersectObjects( objects, recursive = true, intersects = [] ) {
  42. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  43. intersectObject( objects[ i ], this, intersects, recursive );
  44. }
  45. intersects.sort( ascSort );
  46. return intersects;
  47. }
  48. }
  49. function ascSort( a, b ) {
  50. return a.distance - b.distance;
  51. }
  52. function intersectObject( object, raycaster, intersects, recursive ) {
  53. if ( object.layers.test( raycaster.layers ) ) {
  54. object.raycast( raycaster, intersects );
  55. }
  56. if ( recursive === true ) {
  57. const children = object.children;
  58. for ( let i = 0, l = children.length; i < l; i ++ ) {
  59. intersectObject( children[ i ], raycaster, intersects, true );
  60. }
  61. }
  62. }
  63. export { Raycaster };
粤ICP备19079148号